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

后端 未结 3 1319
天涯浪人
天涯浪人 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:58

    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.

提交回复
热议问题