c++ - 如何对 std::map 的值使用基于范围的 for 循环?

标签 c++ c++11 stl

我正在尝试使用 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/

相关文章:

c++ - 哪些 C 结构出现在 std 命名空间中?

c++ - 如何在 Linux 中的 GDB/Nemiver 中显示 C++ STL 容器

c++ - 将 std::stringstream 数据高效解析为 std::vector<std::vector<double>>

c++ - 如何修改类中的值? (C++)

c++ - 互斥保护 : is there any automated protection mechanism for objects?

c++ - 从指向具有可变数量参数的函数的指针映射调用函数

c++ - solaris (x86) 上std::basic_string 的一些疑惑

c++ - 两个序列与 STL 的匹配数

c++ - 打印 map 中包含的集合的内容

c++ - uintX_t 和 intX_t 类型的打印保证