Difference between std::remove and erase for vector?

后端 未结 8 1900
失恋的感觉
失恋的感觉 2020-12-12 18:42

I have a doubt that I would like to clarify in my head. I am aware of the different behavior for std::vector between erase and std::remove

相关标签:
8条回答
  • 2020-12-12 19:40

    Kind of. Algorithms such as remove work on iterators (which are an abstraction to represent an element in a collection) which do not necessarily know which type of collection they are operating on - and therefore cannot call members on the collection to do the actual removal.

    This is good because it allows algorithms to work generically on any container and also on ranges that are subsets of the entire collection.

    Also, as you say, for performance - it may not be necessary to actually remove (and destroy) the elements if all you need is access to the logical end position to pass on to another algorithm.

    0 讨论(0)
  • 2020-12-12 19:40

    Try following code to get better understanding.

    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
    const auto newend (remove(begin(v), end(v), 2));
    
    for(auto a : v){
        cout << a << " ";
    }
    cout << endl;
    v.erase(newend, end(v));
    for(auto a : v){
        cout << a << " ";
    }
    
    0 讨论(0)
提交回复
热议问题