Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector removing elements which fulfill some conditions

Tags:

c++

stl

vector

As the title says I want to remove/merge objects in a vector which fulfill specific conditions. I mean I know how to remove integers from a vector which have the value 99 for instance.

The remove idiom by Scott Meyers:

vector<int> v; v.erase(remove(v.begin(), v.end(), 99), v.end()); 

But suppose if have a vector of objects which contains a delay member variable. And now I want to eliminate all objects which delays differs only less than a specific threshold and want to combine/merge them to one object.

The result of the process should be a vector of objects where the difference of all delays should be at least the specified threshold.

like image 691
antibus Avatar asked Jun 24 '13 08:06

antibus


People also ask

How do I remove a specific element from a vector position?

vector::erase() erase() function is used to remove elements from a container from the specified position or range.

How do I remove a specific element from a vector in C++?

The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.

Which method removes all elements from vector?

The removeAll() method of Java Vector class deletes all the elements from the vector that are present in the specified collection.

How do you remove a random element from a vector?

The idea is to swap the last element and an element you want to remove and then pop_back() . If you need to remove the last elemtent - just pop_back() . The order of the vector will not be the same but you get a fast remove method.


2 Answers

std::remove_if comes to the rescue!

99 would be replaced by UnaryPredicate that would filter your delays, which I am going to use a lambda function for.

And here's the example:

v.erase(std::remove_if(     v.begin(), v.end(),     [](const int& x) {          return x > 10; // put your condition here     }), v.end()); 
like image 147
Bartek Banachewicz Avatar answered Sep 23 '22 18:09

Bartek Banachewicz


C++20 introduces std::erase_if for the very purpose of the objective in this question.

It simplifies the erase-remove idiom for std::vector, and is implemented for other standard containers, including std::string.

Given the example in the current accepted answer:

v.erase(std::remove_if(     v.begin(), v.end(),     [](const int& x) {          return x > 10; // put your condition here     }), v.end()); 

You can now make the same logic more readable as:

std::erase_if( v, [](const int& x){return x > 10;} ); //   container ^  ^ predicate 
like image 22
Drew Dormann Avatar answered Sep 22 '22 18:09

Drew Dormann