如果set的元素是自定义的结构,需要实现一个比较的函数对象。
std::set<Key,Compare,Allocator>::set
自定义结构体
struct Box {
int m1;
int m2;
int m3;
int m4;
};
方案一:定义一个自定义结构的比较类,并自定义operator()函数
struct BoxCmp {
bool operator() (const Box& b1, const Box& b2) {
if (b1.m1 != b2.m1) return b1.m1 < b2.m1;
if (b1.m2 != b2.m2) return b1.m2 < b2.m2;
if (b1.m3 != b2.m3) return b1.m3 < b2.m3;
return b1.m4 < b2.m4;
}
};
定义:
std::set<Box, BoxCmp> set1;
方案二:自定义operator<函数
bool operator< (const Box& b1, const Box& b2) {
if (b1.m1 != b2.m1) return b1.m1 < b2.m1;
if (b1.m2 != b2.m2) return b1.m2 < b2.m2;
if (b1.m3 != b2.m3) return b1.m3 < b2.m3;
return b1.m4 < b2.m4;
}
定义:
std::set<Box, std::less<Box>> set2;
方案三:使用把自定义结构的数据成员拼接成一个std::tuple,当作set的元素,因为tuple重载了operator<
定义:
std::set<std::tuple<int, int, int, int>> set3;