C++ 11 - 基于范围的二维地图循环

Bob*_*bog 1 c++ dictionary multidimensional-array auto c++11

我有一个二维地图,我这样说:

typedef std::map<std::string, std::map<std::string, Objective>> objectives_t;
Run Code Online (Sandbox Code Playgroud)

我想将这个2d地图的内容保存到文件中.

所以我尝试了类似的东西,受到我在网络上找到的一些代码的启发:

for (auto const &subject : m_objectives) {
    for (auto const &objective : m_objectives[subject.first]) {
        //Print the objective
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当然,这不起作用.我该怎么办?我不确定什么是主题和目标(他们是一些迭代器吗?).

在第二行,我得到:

error: passing 'const objectives_t {aka const std::map<std::basic_string<char>, std::map<std::basic_string<char>, Objective> >}' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string<char>; _Tp = std::map<std::basic_string<char>, Objective>; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::map<std::basic_string<char>, Obj|
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 8

你的外围循环是正确的.但内心应该迭代subject.second

for (auto const &subject : m_objectives) {
    for (auto const &objective : subject.second) {
        // print out objective.second
    }
}
Run Code Online (Sandbox Code Playgroud)

这是因为在第一个基于范围的for循环之后,subject有类型

std::pair<const std::string, std::map<std::string, Objective>> const&
Run Code Online (Sandbox Code Playgroud)

所以每个项目都是

subject.first    // std::string
subject.second   // std::map<std::string, Objective>
Run Code Online (Sandbox Code Playgroud)

然后,当你迭代时subject.second,你objective现在是一个

std::pair<const std::string, Objective> const&
Run Code Online (Sandbox Code Playgroud)

所以再次拉开元素

objective.first    // std::string
objective.second   // Objective
Run Code Online (Sandbox Code Playgroud)

  • @Bobog是的,但是1.你已经完成了找到价值所需的工作,两次这样做没有意义; 2.你应该在`const`贴图上使用`map.at(key)`,因为如果键不存在,`map [key]`会添加一个默认构造的值,因此非``const`. (2认同)