你如何在std :: map的值上使用基于范围的for循环?

Gle*_*ing 0 c++ stl c++11

我正在尝试使用基于范围的for循环std::map::operator[]迭代a的值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;
 }
Run Code Online (Sandbox Code Playgroud)

这是编译器的错误消息:

Test.c++:18:19: error: no viable overloaded operator[] for type 'const map<int, set<int> >'
    for (int v : m[2])
Run Code Online (Sandbox Code Playgroud)

后续问题是,鉴于at()有两个版本,为什么不存在两个版本的[]?

T.C*_*.C. 5

map::operator[]如果找不到密钥,则将新元素插入到地图中,因此它不能const,也不能在a上调用const map.

m.at(2)改用.