1

I have a vector with 3 tuples in it. I want to delete all tuples with the second value 4. this is my code:

int main() {

    tuple thing1 = make_tuple(1, 4, 2, 2);
    tuple thing2 = make_tuple(2, 2, 2, 2);
    tuple thing3 = make_tuple(3, 4, 2, 2);

    vector<thing> things = {thing1, thing2, thing3};

    int index = 0;
    for (vector<thing>::iterator it = things.begin(); it != things.end(); ++it) {
        if (get<1>(*it) == 4) {
            things.erase(things.begin()+index);
        } else {
            index++;
        }
    }
}

But this code delete all of them. can anyone help me please ? Thank you so mush :)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Ali Abbasifard
  • 398
  • 4
  • 22

1 Answers1

3

Answer adopted from std::vector removing elements which fulfill some conditions. With the remove_if function template one could do,

things.erase(std::remove_if(
things.begin(), things.end(),
[](const thing& x) -> bool{ 
    return get<1>(x) == 4; // put your condition here
}), things.end());

See an example at C++ Shell.

rranjik
  • 690
  • 9
  • 21