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;
}
}
}
You’re looking for
nas an element, but are also using it as an index. I don’t think this is what you want.If you replace
(n-1)bya, it should work:Alternative way to remove a single element, using
findanderase: