Search code examples
c++c++11stdvector

Select specific elements from a vector


I have a vector v1, and a boolean vector v2 of the same size. I want to delete from v1 all values such that the parallel element of v2 is false:

vector<int> v3; // assume v1 is vector<int>
for (size_t i=0; i<v1.size(); i++)
    if (v2[i])
        v3.push_back(v1[i]);
v1=v3;

Is there a better way to do it?

  • in C++03
  • in C++11

Solution

  • size_t last = 0;
    for (size_t i = 0; i < v1.size(); i++) {
      if (v2[i]) {
        v1[last++] = v1[i];
      }
    }
    v1.erase(v1.begin() + last, v1.end());
    

    Same as yours essentially, except it works in-place, not requiring additional storage. This is basically a reimplementation of std::remove_if (which would be difficult to use directly, because the function object it uses is given a value, not an index or iterator into the container).