问题
In C++, how can I delete an element from a vector?
- Delete it right from where it is, i.e. let the vector resize
- Swap the element to be deleted with the last element s.t. pop_back() can be used (which I hope doesn't involve copying everything around...)
For (1), I've tried the following, but I'm not quite sure if it does what it is supposed to do (remove the item passed to removeItem() ), and it doesn't seem very elegant:
vector<Item*> items;
// fill vector with lots of pointers to item objects (...)
void removeItem(Item * item) {
// release item from memory
if (int i = getItemIdIfExists(item) != -1) {
items.erase (items.begin()+i);
}
}
int getItemIdIfExists(Item * item) {
// Get id of passed-in Item in collection
for (unsigned int i=0; i<items.size(); i++) {
// if match found
if (items[i] == item) return i;
}
// if no match found
return -1;
}
回答1:
void removeItem(Item*item){
for(int i=0; i<items.size(); i++){
if (items[i]==item){
swap(items[i], items.back());
items.pop_back();
return;
}
}
}
Though, if the order doesn't matter, why not just use a std::set
?
回答2:
The standard remove+erase idiom removes elements by value:
#include <vector>
#include <algorithm>
std::vector<int> v;
v.erase(std::remove(v.begin(), v.end(), 12), v.end());
remove
reorders the elements so that all the erasees are at the end and returns an iterator to the beginning of the erasee range, and erase
actually removes the elements from the container.
This is as efficient as you can get with a contiguous-storage container like vector
, especially if you have multiple elements of the same value that all get erased in one wash.
回答3:
Delete it right from where it is, i.e. let the vector resize
That's what erase
does.
Swap the element to be deleted with the last element s.t. pop_back() can be used (which I hope doesn't involve copying everything around...)
That's what remove
does, except that it preserves the order of the remaining objects so it does involve copying everything around.
What you've done could be written as:
items.erase(
std::remove(
items.begin(), items.end()
, item
)
, items.end()
);
The difference with your code being that this will actually remove all items valued item
, instead of just the first one.
来源:https://stackoverflow.com/questions/7869114/erasing-element-from-vector