Pop a Specific Element off a Vector in C++
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 4...
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
4 Answers
//erase the i-th element
myvector.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 element
myvector.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;
}