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

后端 未结 3 1316
天涯浪人
天涯浪人 2021-01-17 21:06

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<

3条回答
  •  离开以前
    2021-01-17 21:49

    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.

提交回复
热议问题