问题
如下代码用于实现set容器中按从大到小排列元素,但是运行时报错,错误为:具有类型“const xxx”的表达式会丢失一些 const-volatile 限定符以调用xxx。
class mycompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void prints(set<int, mycompare> s)
{
for (set<int, mycompare>::iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
set<int, mycompare> s;
s.insert(10);
s.insert(30);
s.insert(20);
s.insert(40);
prints(s);
return 0;
}
出错原因
在C++中,如果比较函数(这里是 mycompare 类的 operator() 函数)被用作 set 的比较准则,那么该比较函数应为 const 函数。如果函数不是const 函数,编译器会认为它有可能修改对象的状态,因此不会将它用于常量对象,而set 要求比较准则可以在常量对象上调用,所以报错。在上述例子中,mycompare 类的 operator() 函数被用作 set 的比较准则,那么该函数应该声明为 const 函数,否则将会导致编译错误。
解决办法
通过在 operator() 函数后加上 const,向编译器保证这个函数不会修改类的成员变量。这样,set 对象就可以在常量上调用该比较函数,而不会导致编译错误。修改如下:
class mycompare
{
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};