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

posted @ 2021-08-23 10:57  鸭子船长  阅读(961)  评论(0编辑  收藏  举报