Is there a convenient way to remove items from a vector (or another stl container) whose values are within an certain interval?
So for example: I got an vector with float values
1.1 1.3 2.2 3.2 4.1 5.2 5.1 1.1 8.0 2.1
and a delta of 0.2, which should lead to the following result
1.1 2.2 3.2 4.1 5.1 8.0
thus removing all “duplicate” items within the delta and keep one of the values within the range.
It can be assumed that the values are “clustered”, where the difference between these is more than 3*delta. Only one value (the mean) of the cluster should be kept, all the others from the cluster should be removed.
For sure, it is possible to iterate with nested loops, but this seems quite complicated, because of the changing iterators, so I thought of a more convenient way. I found remove_if for example, but this function cannot “compare”.
Thanks for suggestions.
You can use
std::uniquewith a predicate:The most used form of
std::uniquetakes no predicate and just removes duplicates from a sequence. But you can write one that implements your filter (in your case, compares two values using a gap) and you are set. Something like:And use it to call
std::unique:Where
vis your vector (or any other sequence).EDIT: Forgot to mention that you need to sort your sequence before using
std::unique. If this is not an option, you have to write your own algorithm.2nd EDIT: For completion, as pointed out by Christian Rau in his comment, you can now erase the items removed from your sequence by using the
erasemethod in it: