How do i insert objects into STL set

前端 未结 3 505
予麋鹿
予麋鹿 2020-12-10 09:04

I am trying to insert a object Point2D into a Point2D set but i am not able to do it, it seems the set works for int and char but not for objects.

I need help to kn

相关标签:
3条回答
  • 2020-12-10 09:09

    std::set<T> requires that std::less<T> is known for the value type T. This is so that it can order its elements, which is fundamental to how it works internally.

    Fix this by defining bool operator<(const Point2D&, const Point2D&), with any logic you choose as long as it satisfies the Strict Weak Ordering.

    This is a requirement of the type, but once you've done this you're good to go.

    0 讨论(0)
  • 2020-12-10 09:30

    I believe a better way for C++ 11 or newer to define the order is to use custom functor, since std::set support that.

    We can see set is defined in header <set> like this:

    template<
        class Key,
        class Compare = std::less<Key>,
        class Allocator = std::allocator<Key>
    > class set;
    

    Hence, to compare based on x for example:

    struct Point2DCmp
    {
        bool operator() (Point2D& p1, Point2D& p2)
        {
            return p1.getX() < p2.getX();
        }
    }
    
    set<Point2D, Point2DCmp> P2D;
    
    0 讨论(0)
  • 2020-12-10 09:32

    You need to implement the operator< overload for your class. For instance, in your class, you can do:

    friend bool operator< (const Point2D &left, const Point2D &right);
    

    Then, outside your class:

    bool operator< (const Point2D &left, const Point2D &right)
    {
        return left.x < right.x;
    }
    

    Edit: As suggested by Retired Ninja, you can also implement this as a regular member-function within your class:

    bool operator< (const Point2D &right) const
    {
        return x < right.x;
    }
    
    0 讨论(0)
提交回复
热议问题