C++ map容器在const修饰下将无法使用"[]"来获取键值 (转)passing ‘’ as ‘xx’ argument discards qualifiers [-fpermissive]
编写程序时无意中发现使用const修饰的map容器变量无法使用重载的[]运算符来获取相应的键值,于是编写测试用例进行验证,如下
#include <map> #include <string> #include <iostream> using namespace std; int main() { map<int, string> test; // 可以 test[16] = "hello"; test[5] = "jack"; test[100] = "fine"; for (auto var : test) cout << var.first << ":" << var.second << endl; cout << test[100] << endl; map<string, int> test1; // 可以 test1["hello"] = 100; test1["I'm"] = 20; test1["fine"] = 4; int tmp = test1["hello"]; cout << tmp << endl; // const 就不能使用[]获取结果 const map<string, int> anot = { {"jack", 2}, {"fun", 5} }; tmp = anot["jack"]; // !!!此处报错,证明const修饰下的map无法使用[] return 0; }
查阅资料后发现,
对于const的对象使用了非const的成员函数:std::map::[]本身不是const成员函数(操作符),对于不在map中的关键字,使用下标操作符会创建新的条目,改变了map
解决方法是使用at成员函数
tmp = anot.at["jack"]; // 可以使用at成员方法来解决
转自:https://blog.csdn.net/benobug/article/details/104903314
参考:https://stackoverflow.com/questions/5973427/error-passing-xxx-as-this-argument-of-xxx-discards-qualifiers
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-08-23 访问vector元素方法的效率比较(转)
2017-08-23 linux c中select使用技巧——计时器(转)
2017-08-23 thread::id
2017-08-23 undefined reference to `std::cout'等错误
2016-08-23 android mk odex问题 push apk 不生效
2015-08-23 判断浮点数是否为0