const map []索引问题
最近开发时遇到一个问题
#include <iostream>
#include <map>
using namespace std;
enum GeColor
{
eRed=0,
eBlue,
eGreen
};
const std::map<GeColor, int>g_map
= { {eRed,1}
,{eBlue,2}
,{eGreen,3} };
int main()
{
cout <</g_map[eRed] << endl;;
return 0;
}
编译出错:
错误 C2678 二进制“[”: 没有找到接受“const std::map<GeColor,int,std::less<GeColor>,std::allocator<std::pair<const GeColor,int>>>”类型的左操作数的运算符(或没有可接受的转换) LearningC++ D:\编程\LearningC++\LearningC++\test 20210416.cpp 24
查找原因在于:
map的[]运算符不是const的,即如果key不存在时,map[key]会自动建立一个有序对<K,V>,其中V为类型的默认值.相当于[]可能改变map类型的成员状态.
解决办法有3种:
1、是去掉函数的const属性,但是这样就改变设计意义了
2、在声明m_scoreTable时加上mutable限定符,如下所示
mutable map<GAMERESULT, RBScore> m_scoreTable;
第2个办法是网友benbear告诉我的,又学到了一招,呵呵
3、不改变原来的声明
代码改为
map<GAMERESULT, RBScore>:: const_ iterator it=m_score.find(res);
assert(it !=m_score.end();
rbscore = it->second;
————————————————
原文链接:https://blog.csdn.net/laomai/article/details/5569627
此外我尝试了用at进行索引也是可以的:
cout <<g_map.at(eRed) << endl;;