我正在尝试使用 std::map::operator[]
通过基于范围的 for 循环迭代 std::map
的值,但以下内容无法编译:
#include <iostream> // cout, endl
#include <map> // map
#include <set> // set
using namespace std;
int main () {
using namespace std;
const map<int, set<int>> m {{2, {201, 202}}, {3, {301, 302}}};
for (int v : m[2])
cout << v << endl;
return 0;
}
这是编译器的错误信息:
Test.c++:18:19: error: no viable overloaded operator[] for type 'const map<int, set<int> >'
for (int v : m[2])
后续问题是,既然有两个版本的 at(),为什么没有两个版本的 []?
最佳答案
map::operator[]
如果未找到键,则将一个新元素插入到映射中,因此它不能是 const
,并且不能在const
map
.
改用m.at(2)
。
关于c++ - 如何对 std::map 的值使用基于范围的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755968/