Daniel
Daniel

Reputation: 2726

Efficient way to remove duplicates

Following the answer in this thread "What's the most efficient way to erase duplicates and sort a vector?". I wrote the following code, but I got an error complaing no match for ‘operator<’ (operand types are ‘const connector’ and ‘const connector’) blahblah...

connector is a class I wrote myself, it basically is a line with two geometry points. uniqCntrs is a std::vector. It has 100% duplicates in it, which means each element has a duplicate, the size of uniqCntrs is quite big. What's wrong with my code, and how to deal with this situation?

std::set<connector> uniqCntrsSet;
for(unsigned int i = 0; i < uniqCntrs.size(); ++i )
{
    uniqCntrsSet.insert(uniqCntrs[i]);
}
uniqCntrs.assign(uniqCntrsSet.begin(), uniqCntrsSet.end());

Edit:

I have no idea how to define < operator for my connector class. I mean it is physically meaningless to say one line is smaller than the other.

Upvotes: 1

Views: 170

Answers (2)

Flovdis
Flovdis

Reputation: 3095

Actually the operator< is just used to efficiently order the map which is used by std::set. It does not need to make any sense. The only requirement is that the operator satisfy the standard mathematical definition of a strict weak ordering.

Look at this point example:

class Point
{
public:
    Point(int x, int y) : x(x), y(y) {
    }

public:
    bool operator==(const Point &other) const {
        return x==other.x && y==other.y;
    }
    bool operator!=(const Point &other) const {
        return !operator==(other);
    }
    bool operator<(const Point &other) const {
        if (x==other.x) {
            return y<other.y;
        } else {
            return x<other.x;
        }
    }

private:
    int x;
    int y;
};

Upvotes: 3

Shoe
Shoe

Reputation: 76240

From cppreference:

std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare.

The second template argument of std::set, Compare, is defaulted to std::less which by defaults compares the objects with operator<. To fix the issue you can simply define operator< for your Key type (connector that is).

Upvotes: 5

Related Questions