zoukankan      html  css  js  c++  java
  • 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=
  • 相关阅读:
    《C#并发编程经典实例》学习笔记—2.4 等待一组任务完成
    Captcha服务(后续2)— 改造Captcha服务之Asp.Net Core项目中如何集成TypeScript
    VS Code调试.Net Core版Hello World
    Visual Studio Code 语言设置
    Captcha服务(后续1)
    css——格式
    作业 5/13
    css选择器
    作业 5/12
    前端——表格标签,表单标签,css
  • 原文地址:https://www.cnblogs.com/zl1991/p/15175009.html
Copyright © 2011-2022 走看看