简体   繁体   English

`[]`运算符导致地图上的编译错误

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

I am trying to get an element from a map in a for loop. 我试图在for循环中从映射中获取元素。 Following the example on cppreference I try this: 按照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;
}

Which gives the following compilation error with gcc: 使用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]++;

If I understand it correctly the problem is that the auto is resolved to a std::pair<const int, int> for which no [] operator is defined. 如果我正确理解的话,问题是auto解析为std::pair<const int, int> ,没有为其定义[]运算符。 I was wondering whether there is a way to get this to work. 我想知道是否有办法使它起作用。

See for the full compilation error here 在此处查看完整的编译错误

How about just 怎么样

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

for your first loop? 你的第一个循环?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM