Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pop a specific element off a vector in c++

Tags:

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

like image 449
kamikaze_pilot Avatar asked Apr 24 '11 02:04

kamikaze_pilot


2 Answers

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

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

like image 63
Dagang Avatar answered Sep 30 '22 03:09

Dagang


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)

like image 42
Ken Bloom Avatar answered Sep 30 '22 03:09

Ken Bloom