Removing an 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 works with elements.

bool condition(double d) {...}

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

What if my condition does not depend on values, but on indices? In other words, if I wanted to remove all elements with an odd index or some arbitrary set of indices, etc.?

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

vector<double> data = ...
std::remove_if (data.begin(), data.end(), ???);
+5
source share
3 answers

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

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

, remove_if , reference 106 - .

+6

. awesomeyi . .

int count = 0;
auto final = std::remove_if (data.begin(), data.end(), [&count](const double d) {
    return (count++) % 2;
});

, - . remove_if ForwardIterators.

, , .

, , , ForwardIterator.

+5

, lambas . :

vector<double> data = {5, 3, 6, 7, 8};

int count = 0;
auto final = std::remove_if (data.begin(), data.end(), [&](const double d) {
    bool b = false;
    if(count % 2) b = true;
    ++count;
    return b;
});

for(auto beg = data.begin(); beg != final; ++beg)
    cout << *beg << endl;

: 5 6 8

+1

All Articles