Reputation: 887
Coming from Java and using the ArrayList class has me all frustrated when trying to learn the C++ equivalent (Vectors).
I'm writing a function that removes a certain int given from a vector of ints. For awhile I could not figure out why it was causing a segmentation fault. After looking at the documentation I realized .erase also removes any element after the one being erased. Which is definitely not what I want to do, so I'm a little lost of how I would go about removing only a single element from a vector without removing the elements after.
Function that I currently have which causes a segmentation fault:
void remove(int n){
for(int a=0; a<list.size(); a++){
if(list.at(a)==n){
list.erase (list.begin()+(n-1));
cout << n << " has been erased" << endl;
break;
}
}
}
Upvotes: 1
Views: 4284
Reputation: 18633
You're looking for n
as an element, but are also using it as an index. I don't think this is what you want.
If you replace (n-1)
by a
, it should work:
list.erase(list.begin()+a);
Alternative way to remove a single element, using find
and erase
:
#include <algorithm>
//...
void removeOne(int n){
vector<int>::iterator found = std::find(list.begin(), list.end(), n) ;
if (found!=list.end())
list.erase(found);
}
Upvotes: 3
Reputation: 67211
std::vector<int> v;
// fill it up somehow
v.erase(std::remove(v.begin(), v.end(), 99), v.end());
// really remove all elements with value 99
Upvotes: 2
Reputation: 127
You'll be needing iterator erase ( iterator first, iterator last );
see here. (http://www.cplusplus.com/reference/stl/vector/erase/)
Upvotes: 0