STL 篇 ----- 关于map容器对自定义类型排序的问题!
hello,我是黑猫 !
今天在写map容器的时候,发现代码对自定义类型排序的时候出错了!
话不多说,先上代码!
#include<iostream>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
class Mycompare
{
public:
bool operator()(const Person &p1, const Person &p2)
{
return p1.m_age <= p2.m_age;
}
};
void myprint(map<Person, int, Mycompare>& m)
{
for (map<Person, int,Mycompare>::iterator it = m.begin(); it != m.end(); it++)
{
cout << it->first.m_name<<" " << it->first.m_age << " " << it->second << endl;
}
}
void test01()
{
map<Person, int, Mycompare> m;
Person P1("aaa",18);
Person P2("bbb", 20);
Person P3("ccc", 30);
Person P4("ddd", 13);
m.insert(make_pair(P1, 1));
m.insert(make_pair(P2, 2));
m.insert(make_pair(P3, 3));
m.insert(make_pair(P4, 4));
myprint(m);
}
int main() {
test01();
system("pause");
return 0;
}
以上代码在vs有些版本中是可以跑得通的! 但在vs2019版本中,是会提示错误的! 具体出现了两个错误
C3848 具有类型“const Mycompare”的表达式会丢失一些 const-volatile 限定符以调用“bool Mycompare::operator ()(const Person &,const Person &)”
C2664 “bool Mycompare::operator ()(const Person &,const Person &)const”:无法将参数 1 从 “const_Kty" 转换成 ”const person &“
解决方案:
1.
bool operator()(const Person& p1, const Person& p2)const
2.
const bool operator()(const Person& p1, const Person& p2)const
以上解决方案来自于网络与自身测试-
聊五毛钱天
这个两种在我自己写代码的时候都有写到,具体也不太清楚,如果有知道的hxd请留言的哦 !
最好都加上的吧!有的时候还是会出现错误,这个编译器就很迷!(vs2019)应该是新增加特性
就比如我都加上了,但还是报出了错误!
还有set容器中的自定义排序也可参考哦!
不早了,晚安!先睡了,希望明天工地的砖不烫手(doge)
最后的最后呢!希望本文对您的编程之路有所帮助!
在使用VS2019时,遇到自定义类型Person在map中排序出错的问题。错误提示涉及const限定符和函数调用。解决方案是为比较函数添加const关键字,使其成为常量成员函数。经测试,此改动可以解决部分问题,但有时可能仍会出现错误。该问题可能与VS2019的新特性有关。对于set容器中的自定义排序,也可参考此解决方案。
586

被折叠的 条评论
为什么被折叠?



