TITLE: stl initialization of multidim array (Newsgroups: comp.std.c++, 18 Oct 96) PROBLEM: "Ole Petter Brunstad" I am new to STL, and I am having problems initializing a multidimentional array. I thought this was the right way: int data[] = { 1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24,25, 26 }; vector > &values(3); for (int i = 0; i < 3; i++) copy(data + i*6, data + i*6 + 6, values[i].begin()); but each values[i] only gets 4 items long (except for the last one that is 6 items long). Can anyone tell me how this should be done? RESPONSE: kanze@gabi-soft.fr (J. Kanze) There are several ways. First, however, what you have written is undefined behavior; I suspect that there are systems or implementations on which it will core dump. (A tip: you really need Cay Horstman's safe STL for experimenting. Unless I'm badly mistaken, it would have generated an error on each of the calls to copy.) As written, the contained vectors never actually contain any elements. Accessing beyond the end of a vector using the iterator (which is what copy will do in your code) does NOT extend the iterator; it is simply undefined behavior. You need something to extend the vector. The simplest solution, or at least the closest to your code, would be to replace the current invocation of copy with: copy( &data[ 6 * i ] , &data[ 6 * i + 6 ] , back_inserter( values[ i ] ) ) ; The back_inserter function returns an iterator which inserts: operator++ is a no-op, and dereferencing causes an additional element to be appended at the end of the container. I would probably tend to reflect the actual data structure in the initialization data as well, using something like: static int const data[][ 6 ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 11 , 12 , 13 , 14 , 15 , 16 } , { 21 , 22 , 23 , 24 , 25 , 26 } , } ; vector< vector< int > > values ; for ( int i = 0; i < sizeof( data ) / sizeof( data[ 0 ] ) ; i ++ ) values.push_back( vector< int >( data[ i ] , data[ i + 1 ] ) ) ; (While I'm at it: can anyone quote a passage from the standard that guarantees that "data[ i + 1 ]" will be a valide end iterator for the begin iterator "data[ i ]"? This works on all implementations I can possibly think of, and I think that there are enough restrictions on the data layout in the C standard to guarantee it, but I'd feel better if someone could confirm its correctness.) For more information concerning this problem, you probably want to read Andy Koenig's article "Copying and Insertion in STL Algorithms", in the Sept. '96 issue of C++ Report. One last point: the code you have written shouldn't compiler under the standard. You didn't really mean for values to be a reference, did you?