TITLE: simple STL copy mistakes (Newsgroups: comp.lang.c++.moderated, 5 Aug 98) HELCK: C & C Helck > I needed to append one vector to another and tried the obvious: > > vector src; > vector dest; > > copy(src.begin(), src.end(), dest.end()); > > And it cored. KANZE: jkanze@otelo.ibmmail.com Normal. Copy doesn't, in itself, do anything to increase the size of the destination. (How could it, if the destination was a built-in array?) And any attempt to dereference or increment an iterator returned by end is undefined behavior. What you need to do is use an insertion iterator -- in this case: copy( src.begin() , src.end() , back_inserter( dest ) ) ; A back_insertor basically returns a reference to itself (and does nothing else) in operator++ and operator*, and defines operator= to do a push_back on the container. HELCK: > Apparently "dest.end()" is a NULL ptr. KANZE: dest.end() is a pointer to one beyond the end of the array, with exactly the same semantics as this would apply in C for a pointer to one beyond the end of the C style array. Dereferencing or incrementing it are undefined behavior. HELCK: > I rewrote my code > to > use a loop and everything is ok. I'm wondering if there is a way to use > one > of the generic functions to do what I want? > > Also shouldn't "end()" return a const_iterator so the compiler could > catch errors > like: > > for ( ii=src.end(); ii != src.begin(); --ii) > ; KANZE: No error there to catch. In fact, if I wanted to iterator in reverse over the container, the above loop would do exactly what I want, at least if I remember to only reference *(i-1) in the loop. Of course, this idiom is encapsulated in the concept of reverse_iterator.