What happens if I use vector::begin() instead of std::back_inserter(vector) for output of set_intersection?

删除回忆录丶 提交于 2019-12-01 15:51:41

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 container c holds enough elements to overwrite. Imagine that c.begin() returns a pointer to an array of size 0 - then you'll see the problem when writing *out++ = 7;.

back_inserter adds every assigned value to a vector (via push_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

 std::set_intersection(a.begin(),a.end(),b.begin(),b.end(),
                       c.begin());

invokes undefined behavior once set_intersection writes something to its output iterator, that is, when the set intersection of a and b isn't empty.

Can a conforming implementation silently extend the vector in this case, so that begin() is in fact an appending OutputIterator like back_inserter is?

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.)

back_inserter inserts the element in the range by calling push_back ( that's why you can't use back_inserter with the range which doesn't provide push_back operation).

So, you won't care about going past the end of the range as push_back automatically expands the container. However, that's not the case with insert using begin().

If you are using begin(), then you have to make sure that destination range is big enough to hold all elements. Failing to do so would instantly transport your code to the realm of undefined behavior.

It compiles fine because you get a valid iterator back from the begin function, but if the vector is empty then you will get back the end iterator, and then continue from there.

It will work only if the destination vector already contains at least as many elements as you try to add, and then it will actually overwrite those elements and not add new.

And adding elements is just what the back_inserter iterator does, it returns an iterator that basically does push_back on the vector.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!