Search code examples
c++vector

pop a specific element off a vector in c++


Suppose I have a vector v and it has three elements: {1,2,3}.

Is there a way to specifically pop 2 from the vector so the resulting vector becomes {1,3}.


Solution

  • Assuming you're looking for the element containing the value 2, not the value at index 2.

    #include<vector>
    #include<algorithm>
    
    int main(){
       std::vector<int> a={1,2,3};
       a.erase(std::find(a.begin(),a.end(),2));
    }
    

    (I used C++0x to avoid some boilerplate, but the actual use of std::find and vector::erase doesn't require C++0x)