#include<cstdio> #include<set> using namespace std; class A { public: int a,b,c; friend bool operator <(A a,A b) { return a.a<b.a; } }; int main() { A a1,a2; a1.a=1;a1.b=2;a1.c=3; a2.a=1;a2.b=3;a2.c=4; set <A> s; s.insert(a1); s.insert(a2); printf("%d\n",s.size());//输出1 return 0; }
为什么会输出1,原因是重载小于号的时候只用了a吗,假如a,b,c都用了就是2.
解决方案
30
10
15
#include <cstdio> #include <cstring> #include <set> using namespace std; class A { public: A(int arg_a, int arg_b, int arg_c) : a_(arg_a), b_(arg_b), c_(arg_c) {} private: int a_, b_, c_; }; inline bool operator <(const A & lhs, const A & rhs) { return memcmp(&lhs, &rhs, sizeof(lhs)) < 0; } int main() { A a1(1, 2, 3), a2(1, 3, 4); set<A> s; s.insert(a1); s.insert(a2); printf("%u\n", s.size());//输出2 return 0; }