Search code examples
c++vector

How to erase multiple elements from std::vector<> by index using erase function?


I have a vector a storing values [0 1 2 3 5] and other vector removelist storing the indexes to be removed [0 1 2] in order to leave [3 5] at the end. When I'm implementing the following code, it would remove items unexpectedly since the vector a will be changing order during the process. Is there any way for me to achieve my target?

 for (int i = 0; i<removelist.size() ; i++)     
    a.erase(a.begin() + removelist[i]);

Solution

  • Reverse the order you remove values, i.e. use the reverse iterators of removelist. This of course relies on removelist being sorted.

    Perhaps something like

    std::sort(removelist.begin(), removelist.end());  // Make sure the container is sorted
    for (auto &i = removelist.rbegin(); i != removelist.rend(); ++ i)
    {
        a.erase(a.begin() + *i);
    }