Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing element from Vector [duplicate]

Tags:

c++

vector

erase

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

  1. Delete it right from where it is, i.e. let the vector resize
  2. 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;
}
like image 493
Ben Avatar asked Mar 25 '26 10:03

Ben


1 Answers

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.

like image 74
Kerrek SB Avatar answered Mar 27 '26 00:03

Kerrek SB