1. 程式人生 > 其它 >C++ map容器在const修飾下將無法使用"[]"來獲取鍵值 (轉)passing ‘’ as ‘xx’ argument discards qualifiers [-fpermissive]

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=