简体   繁体   中英

Erasing element from Vector

In C++, how can I delete an element from a vector?

  1. Delete it right from where it is, ie let the vector resize
  2. Swap the element to be deleted with the last element st 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;
}

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.

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 ?

Delete it right from where it is, ie let the vector resize

That's what erase does.

Swap the element to be deleted with the last element st 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM