关键点:自定义类需要重载”<”运算符,并且 重载的函数”operator<”参数(如果传的是引用)和函数的类型都要为const。如果参数是非const对象的引用,则会报如下错误:二进制“<”: 没有找到接受“const Interval”类型的右操作数的运算符(或没有可接受的转换)(如果参数非引用,则不会报此错误);如果函数非const,则会报如下错误:二进制“<”: 没有找到接受“const Interval”类型的左操作数的运算符(或没有可接受的转换)。
原因:容器对自定义类对象进行排序时,希望能作用在const对象上,而const对象是不能调用该类的非const的成员函数的。
下面给出一个例子:
#include <iostream>
#include <set>
using namespace std;
class Interval {
public:
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
bool operator<(const Interval &B)const
{
if (start != B.start)
return start < B.start;
else
return end < B.end;
}
};
int main()
{
multiset<Interval> intSet;
Interval int1(2, 5), int2(3, 4), int3(1, 4);
intSet.insert(int1);
intSet.insert(int2);
intSet.insert(int3);
for (multiset<Interval>::iterator it=intSet.begin();it!=intSet.end();++it)
{
cout<<it->start<<' '<<it->end<<endl;
}
return 0;
}
运行结果: