//报错,因为模板的第二个默认参数是std::less<Key>类,它只能对内置类型进行<比较,无法识别自定义类型的<操作
set<Point> number = { Point(1, 2),Point(-2, 3) };3种解决方法:
1、重载针对于Point类的operator<()
bool operator<(const Point &lhs, const Point &rhs) { cout << "bool operator<(const Point &, const Point &)" << endl; if(lhs.getDistance() < rhs.getDistance()) { return true; } else { return false; } } set<Point> number = { Point(1, 2),Point(-2, 3) }; //不会报错
2、在std命名空间里实现struct less针对Point的特化版本
namespace std { template <> struct less<Point> { bool operator()(const Point &lhs , const Point &rhs) { if (lhs.getDistance() < rhs.getDistance()) { return true; } else { return false; } } }; } set<Point , std::less<Point>> number = { Point(1, 2),Point(-2, 3) };
3、自定义函数对象实现Point类的<比较
struct Comapation { bool operator()(const Point &lhs, const Point &rhs) const { cout << "bool operator()(const Point &, const Point &) const" << endl; if(lhs.getDistance() > rhs.getDistance()) { return true; } else { return false; } } }; set<Point , Comapation> number = {Point(1, 2),Point(-2, 3)};