Search code examples
c++vectorerase

delete special object from vector c++


I have a vector of int

vector<int> p;

now I want to delete one of its items that is equal to 3. there is no remove like p.remove(3)

but there is a erase but at first I should I find it. there were two questions about this available in stackoverflow. both of them said that we should find it by

std::remove(p.begin(), p.end(), 3) 

but this code isn't compiled. it said function does not take 3 arguments.


Solution

  • Use Erase Remove Idiom .

    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <vector> 
    
    int main()
    {
        using namespace std;
        vector<int> v = {1, 2, 3, 3, 4};
    
        v.erase(find(begin(v), end(v), 3));  // remove first 3
        // v.erase(remove(begin(v), end(v), 3), end(v));  // remove all 3
    
        copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
    }
    

    Vectors erase method takes one or two iterators. The first one, erases everthing from the specified position to the end. std::remove from <algorithm> moves all matching elements to the end of the sequence and returns an iterator to the position of the new end. You can use this iterator for erase. If you want to remove the first matching element, use std::find to retrieve an iterator to the first element and pass that to erase.