简体   繁体   中英

To Capture iterator difference in a list and use it to erase elements of a vector

I have a vector from which I want to remove all odd numbers. I did it like the following

#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v={1,2,3,4,5,6,7,8,9};
        std::vector<int>::iterator it2=v.begin();
    while(it2!=v.end())
    {
    for ( it2= v.begin();it2!=v.end();++it2)
    {
        if ((*it2)%2==1){
            v.erase(it2);
            break;
            }
    }
    }
    for(it2=v.begin(); it2!=v.end();++it2)
        std::cout<<*it2<<" ";

}

It works :) This is just crude. I wanted to set up a vector list and "capture" the iterator - begin() values and erase with one more loop. But Now i think thats not possible. as after each erase the saved values wont be valid. Do you have a better and efficient way???

You should probably use something like this:

v.erase(std::remove_if(v.begin(), v.end(), [](int i){ return bool(i % 2); }), v.end());

The std::remove_if() algorithms moves the non-removed elements to the front of the sequence with a single pass. It then returns an iterator to the end of the non-removed sequence. This iterator is then used as the start of the sequence which should be verase() d together with v.end() to indicate the end of the sequence. You won't get a more efficient algorithm.

You really need to learn the STL algorithms that do the work for you. There is no need to be writing error-prone loops.

Erasing elements based on some criteria is easily done using the erase() / remove_if() idiom as shown in the other answers. If you don't have C++11, then the following also suffices:

bool IsOdd(int x) { return bool(x%2); }

...
v.erase(std::remove_if(v.begin(), v.end(), IsOdd), v.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM