How to remove almost duplicates from a vector in C++

c++, duplicates, floating-accuracy, vector

Solution

First sort your vector using `std::sort`. Then use `std::unique` with a custom predicate to remove the duplicates.

std::unique(v.begin(), v.end(), 
            [](double l, double r) { return std::abs(l - r) < 0.01; });
// treats any numbers that differ by less than 0.01 as equal

Live demo

Problem

I have an std::vector of floats that I want to not contain duplicates but the math that populates the vector isn't 100% precise. The vector has values that differ by a few hundredths but should be treated as the same point. For example here's some values in one of them: ``` ... X: -43.094505 X: -43.094501 X: -43.094498 ... ``` What would be the best/most efficient way to remove duplicates from a vector like this.

Original source