Pull a specific element from a vector in C ++

so suppose I have a vector called v, and it has three elements: 1,2,3

there is a way to specifically set 2 of the vector so that the resulting vector becomes

1.3

+7
source share
4 answers

Assuming you're looking for an element containing the value 2 , not the value in 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 pattern, but the actual use of std::find and vector::erase does not require C ++ 0x)

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

(counting the first element in a vector as i=0 )

+17
source

Also, be sure to use erase-remove idiom if you are removing multiple items.

+5
source
 #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; } 
+1
source

All Articles