Search code examples
c++vectorindexingiteratorremove-if

Removing by index from a C++ vector using remove_if


We can use remove_if in C++ to remove elements from a vector in linear time based on a predicate that operates on the elements.

bool condition(double d) {...}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), condition);

What if my condition depends not on the values, but on the indices? In other words, if I wanted to remove all the odd-indexed elements, or some arbitrary index set, etc?

bool condition(int index) {//returns whether this index should be removed}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), ???);

Solution

  • You can use pointer arithmetic to find the index of a specific element that std::remove_if passes to the predicate:

    std::remove_if(data.begin(), data.end(),
                   [&data](const double& d) { return (&d - &*data.begin()) % 2); });
    

    Note that remove_if passes the result of dereferencing an iterator, and that's guaranteed to be a reference per Table 106 - Iterator requirements in the Standard.