Search code examples
c++c++11vectorstdvector

std::vector.erase() only erases half of what it should


I have a program where I have to delete some entries of a vector of structs. Im doing it like this

  for(int i=0; i<molec.size(); i++)
    {
      if(!molec[i].mine)
        molec.erase(molec.begin()+i);
    }

molec.mine is a boolean defined in the struct. The problem is that when I do this, it erases exactly half of the elements with molec.mine=false. I tried to search for some alternatives and found that I could do it with

vector.erase(std::remove(vec.begin(),vec.end(),1963),vec.end());

The thing with this is that I don't know how to do it with a vector of structs.

How can I solve this problem?


Solution

  • You are probably looking for std::remove_if. As in

    molec.erase(
      std::remove_if(
        molec.begin(), molec.end(),
        [](const auto& elem) { return !elem.mine; }),
      molec.end());