so suppose I have a vector called 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

5

Best Answer


//erase the i-th elementmyvector.erase (myvector.begin() + i);

(Counting the first element in the vector as as i=0)

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)

Also, remember to use the erase-remove idiom if you are removing multiple elements.

#include <iostream>#include <vector>using namespace std;int main (){unsigned int i;vector<unsigned int> myvector;// set some values (from 1 to 10)for (i=1; i<=10; i++) myvector.push_back(i);// erase the 6th elementmyvector.erase (myvector.begin()+5);// erase the first 3 elements:myvector.erase (myvector.begin(),myvector.begin()+3);cout << "myvector contains:";for (i=0; i<myvector.size(); i++)cout << " " << myvector[i];cout << endl;return 0;}

From C++ 20, we can use std::erase for removing multiple elements.

(no need for "erase-remove idiom")

#include <iostream>#include <vector>int main(){std::vector<int> v{1,2,2,3,4,5};std::erase(v, 2);for(auto e : v) std::cout << e << " ";std::cout << '\n';// output: 1 3 4 5}