簡體   English   中英

`[]`運算符導致地圖上的編譯錯誤

[英]`[ ]` operator leads to compile error on map

我試圖在for循環中從映射中獲取元素。 按照cppreference上的示例,我嘗試以下操作:

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int, int> mapping;

    mapping.insert(pair<int, int>(11,1));
    mapping.insert(pair<int, int>(12,2));
    mapping.insert(pair<int, int>(13,3));

    for (const auto &it : mapping)
        mapping[it]++;


    cout << "array: ";
    for (const auto &it : mapping)
        cout << it.second << " ";

    return 0;
}

使用gcc會產生以下編譯錯誤:

main.cpp: In function 'int main()':
main.cpp:15:16: error: no match for 'operator[]' (operand types are 'std::map<int, int>' and 'const std::pair<const int, int>')
         mapping[it]++;

如果我正確理解的話,問題是auto解析為std::pair<const int, int> ,沒有為其定義[]運算符。 我想知道是否有辦法使它起作用。

在此處查看完整的編譯錯誤

怎么樣

for (auto &it : mapping)
    ++it.second;

你的第一個循環?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM