今天在学习C++的map容器排序时,跟着老师的课程做map容器的降序排序时编译报错,报错提示:
error: no matching function for call to object of type 'const MyCompare'
对着老师的代码看了半天,确认一个字符都没有敲错。但是视频中老师的可以正常输出,我这一摸一样的代码确报错。搞的很是恼火。。。
我的代码:
#include <iostream>
#include <string>
#include <map>
using namespace std;
//map容器排序
//排序用仿函数
class MyCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
//打印输出函数
void printMap(const map<int, string, MyCompare> &m)
{
for (map<int, string, MyCompare>::const_iterator it = m.begin(); it != m.end(); it++)
{
cout << "序号:" << (*it).first << " 姓名:" << it->second << endl;
}
cout << endl;
};
void test01()
{
//创建map容器对象
map<int, string, MyCompare> m1;
//插入数据
m1.insert(make_pair(5, "黄忠"));
m1.insert(make_pair(3, "张飞"));
m1.insert(make_pair(4, "赵云"));
m1.insert(make_pair(6, "马超"));
m1.insert(make_pair(1, "刘备"));
m1.insert(make_pair(2, "关羽"));
printMap(m1);
};
int main()
{
test01();
return 0;
};
错误截图:
看提示,似乎说是MyCompare类少了const,好,加const:
class MyCompare
{
public:
bool operator()(const int v1, const int v2)
{
return v1 > v2;
}
};
继续编译还是报错。。。
最后查资料,啥的搞了一个多小时。最后在重载函数后面添加了const,再编译就好了:
class MyCompare
{
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};
具体原因最后还是不知道为啥,期望看到本文的大神帮忙解答下。