I have been using the highly concise and intuitive C++ syntax for finding the intersection of two sorted vectors and putting the result in a third vector:
vector<bar> a,b,c;
//...
std::set_intersection(a.begin(),a.end(),b.begin(),b.end(),
std::back_inserter(c));
This should set c to intersection(a,b), assuming a and b are sorted.
But what if I just use c.begin() (I thought I saw an example somewhere of this, which is why I did):
std::set_intersection(a.begin(),a.end(),b.begin(),b.end(),
c.begin());
set_intersection expects an OutputIterator at that parameter. The standard I believe requires only that c.begin() return a forward iterator, which I suppose might or might not be an OutputIterator.
Anyway, the code with c.begin() compiled under clang.
What is guaranteed to happen under the standard? If this compiles, what is likely to happen - that is, when the iterator returned by c.begin() is eventually incremented past the end of the vector, and an attempt is made to access the element pointed to, what must/may happen? Can a conforming implementation silently extend the vector in this case, so that begin() is in fact an appending OutputIterator like back_inserter is?
I'm asking this mainly to understand how the standard works with iterators: what's really going on, so I can move beyond copy-and-paste in using the STL.
The important requirement for an output iterator is that it be valid and write-able for the range
[out, out+size of output).Passing
c.begin()will lead to the values being overwritten which only works if the containercholds enough elements to overwrite. Imagine thatc.begin()returns a pointer to an array of size 0 - then you'll see the problem when writing*out++ = 7;.back_inserteradds every assigned value to avector(viapush_back) and provides a concise way of making the STL-algorithms extend a range - it overloads the operators that are used for iterators appropriately.Thus
invokes undefined behavior once
set_intersectionwrites something to its output iterator, that is, when the set intersection ofaandbisn't empty.Of course. It's undefined behavior. (This is a humorous approach of telling you that you shouldn't even consider using this, no matter the effects on any implementation.)