Saturday, December 4, 2010


Given: vector v1, v2; v1.size() == v2.size(), and copy(v1.begin(), v1.end(), v2.begin());

The above statement works, without needing an ostream_iterator() wrapped around the v2.

Since v2.begin() is already an iterator, ostream_iterator() is not used here.

Typical bugs with the above copy() include:
1) Not having enough space available in v2; and
2) Trying to use v2.end() as the third argument, in an attempt to append the v1 data to the v2 vector.

Note that v2.end() points 1 item past the data part of v2, so it is uninitialized memory.

Note also that pointers are also iterators, so the following code is also valid:

int int_array1[5] = {1,2,3,4,5}, int_array2[5];
int *p_int_array1 = &int_array1[0];
int *p_int_array2 = &int_array2[0];

copy(p_int_array1, p_int_array1+sizeof(int_array1), p_int_array2);
vector<int> vec;
copy(p_int_array1, p_int_array1+sizeof(int_array1), vec.begin());

Note that p_int_array1+sizeof(int_array1) points one item past the data in int_array1, which is similar to vec.end();

Also note (see below), when inserter() is used, vec.end() is not a problem as the third argument to copy().

No comments:

Post a Comment