c++ vector erase

代码示例

#include 
#include 
#include 

using namespace std;

int main()
{
    std::vector vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector::iterator it;


    cout<<"before size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    int lookFor = 2;
    std::remove(vec.begin(), vec.end(), lookFor);
    cout<<"after remove size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    lookFor = 3;
    std::remove_if(vec.begin(), vec.end(), [vec,lookFor](int n){
        return n==lookFor;
    });
    cout<<"after remove_if size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    lookFor = 4;
    auto el = std::find(vec.begin(), vec.end(), lookFor);
    vec.erase(el);
    cout<<"after erase el size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    lookFor = 5;
    vec.erase(std::remove_if(vec.begin(), vec.end(), [vec, lookFor](int n) {return n==lookFor;}), vec.end());
    cout<<"after erase remove_if size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    for (it = vec.begin(); it != vec.end(); it++)
    {
        it = vec.erase(it);
    }
    cout<<"after erase it++ size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    
    for (it = vec.begin(); it != vec.end();)
    {
        it = vec.erase(it);
    }
    cout<<"after erase it= size="<< vec.size() << std::endl;
    for (it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

结果

before size=10
1 2 3 4 5 6 7 8 9 10 
after remove size=10
1 3 4 5 6 7 8 9 10 10 
after remove_if size=10
1 4 5 6 7 8 9 10 10 10 
after erase el size=9
1 5 6 7 8 9 10 10 10 
after erase remove_if size=8
1 6 7 8 9 10 10 10 
after erase it++ size=4
6 8 10 10 
after erase it= size=0

你可能感兴趣的:(c++,c++)