How do i insert objects into STL set

前端 未结 3 507
予麋鹿
予麋鹿 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: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 like this:

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

    Hence, to compare based on x for example:

    struct Point2DCmp
    {
        bool operator() (Point2D& p1, Point2D& p2)
        {
            return p1.getX() < p2.getX();
        }
    }
    
    set P2D;
    

提交回复
热议问题