Search code examples
c++vectoreraseerase-remove-idiom

Erasing elements in a vector


So I have a vector of unsigned ints (vector<unsigned int> is called vector1). I have another vector of a struct I created (vector<struct> is called vector2). vector<int> holds an integer that is the index of the vector<struct>. For example, let's say that vector<int = {5, 17, 18, 19}. That means vector2.at(5) == vector2.at(vector1.at(0)).

In the struct, I have a bool variable called var. In most cases, var is false. I want to delete all of the elements in vector1 that have var = true.

What I did was:

for (unsigned int i = 0; i < vector1.size(); i++)
{
   if (vector2.at(vector1.at(i)).var)
    vector1.erase(vector.begin() + i);
}

The only problem with this is that it does not delete all of the true elements. I have run the for loop multiple times for all values to be delete. Is this the correct behavior? If it is not, where did I go wrong?


Solution

  • You have to use the erase-remove idiom to delete elements from a vector.

    v.erase(std::remove(v.begin(), v.end(), value), v.begin);
    

    std::remove moves the elements to the end of the vector and erase will erase the element from the vector.