在学习C++STL中的set时,尝试利用仿函数,改变set的排序规则,代码如下
#include<iostream>
#include<cstring>
#include<algorithm>
#include<set>
using namespace std;
class Mypx {
public:
bool operator() (int a, int b) {
return a > b;
}
};
void test01() {
set<int,Mypx> s1;
s1.insert(10);
s1.insert(20);
s1.insert(40);
s1.insert(30);
for (set<int,Mypx>::iterator it = s1.begin(); it != s1.end(); it++) {
cout << *it << ' ';
}
}
int main() {
test01();
}
编译器报错
错误 C3848 具有类型“const Mypx”的表达式会丢失一些 const-volatile 限定符以调用“bool Mypx::operator ()(int,int)” Project2 C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\include\xutility 1160
解决方法
在仿函数中,重载()的函数后面加const
class Mypx {
public:
bool operator() (int a, int b) const{
return a > b;
}
};
原因
-
安全性:通过声明成员函数为const,可以确保在该函数内部不会对类的数据成员进行修改,从而提高代码的安全性。
-
可用性:当您在const对象上调用一个const成员函数时,可以确信这个函数不会引起对象状态的改变,这使得在使用const对象时也能够使用这个函数。
-
清晰性:标记成员函数为const可以使其接口更清晰地表明其行为,其他开发人员在使用和阅读代码时可以更容易地理解函数的作用。