Can you return an array?

Started by
12 comments, last by Fruny 19 years, 2 months ago
Same principle as 1D - either pass the output variable as parameter or use some STL container:
bool load( const std::string& fileName, std::vector< std::string > & out ) {        std::ifstream fin;       bool result = false;        fin.open( fileName.c_str() );    if ( fin.is_open() ) {                   char line[128];         while ( fin.good() ) {            fin.getline( line, sizeof ( line ) );            out.push_back ( line );        }            fin.close();        result = true;    }        return result;}
Advertisement
Quote:Original post by mcgrane66
But can anyone now tell me, can i return a 2d array?


2D arrays are generally just manipulated as 1D array, using explicit addressing. i.e. you don't do foo[j] but foo[i*row_size+j]. The alternative is to use nested containers (in essence, creating an array of arrays), which is a very different beast from a "2D array", since 2D arrays are a single, contiguous block of memory. The 2D addressing syntax is just ... syntactic sugar.

If you really want multidimensional arrays you can pass around, look at boost::multi_array.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I wouldn't recommend returning an STL string from a function, at least not if it's very large. Speed difference between passing in the string as a reference and returning one is quite signifficant...

...and if i may be picky, if you can find the total size for the file, you should .resize() your vector and use the ifstream::read() function to fill it.

I just wanted to point this out before you get into a habit. I did, and recently ran my head into a wall when my .obj loader tried to load a high-poly object, and the load time exceeded...well several minutes...on one object...[grin]
----------------------------------------------------------------------------------------------------------------------"Ask not what humanity can do for you, ask what you can do for humanity." - By: Richard D. Colbert Jr.
Quote:Original post by Android_s
I wouldn't recommend returning an STL string from a function, at least not if it's very large. Speed difference between passing in the string as a reference and returning one is quite signifficant...


RVO.

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement