`[ ]` 运算符导致地图编译错误
`[ ]` 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>
。我想知道是否有办法让它工作。
查看完整编译错误here
怎么样
for (auto &it : mapping)
++it.second;
你的第一个循环?
我试图在 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>
。我想知道是否有办法让它工作。
查看完整编译错误here
怎么样
for (auto &it : mapping)
++it.second;
你的第一个循环?