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}
.
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}
.
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)
std::set
or std::unsorted_set
instead. –
Stringed //erase the i-th element
myvector.erase (myvector.begin() + i);
(Counting the first element in the vector as as i=0
)
pop
deletes an item by index (Todd's answer), and remove
deletes an item by value (my answer). –
Stringed 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)
O(n)
, aka it needs to search through the whole vector. If you have a sorted vector, you can try lower_bound
–
Be std::set
or std::unsorted_set
instead. –
Stringed 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;
}
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
}
© 2022 - 2024 — McMap. All rights reserved.
O(n)
, aka it needs to search through the whole vector. If you have a sorted vector, you can trylower_bound
– Be