c++ - 遍历 unordered_map cpp 的 unordered_map 中的元素

标签 c++ unordered-map

假设我有一个 unordered_map 定义如下:

unordered_map<int, unordered_map<int, int>> f_table;
f_table[1][3] = 10;
f_table[1][2] = 1;
f_table[1][1] = 2;
f_table[2][3] = 11;
f_table[2][2] = 22;
f_table[2][1] = 4;
f_table[3][3] = 1;
f_table[3][2] = 3;
f_table[3][1] = 2;

我想对 f_table[1] 中的所有元素求和,加起来应该是 13。我该怎么做?

最佳答案

一种方法是像这样使用 std::accumulate:

#include <numeric>

const int result = std::accumulate(f_table[1].cbegin(), f_table[1].cend(),
    0, [](int result, const auto& entry){ return result + entry.second; });

请注意,正如@StoryTeller 在评论中指出的那样,您可能更喜欢此算法的并行版本,它将附带完全符合 C++17 的实现,即 std::reduce .

另一个选项是基于范围的 for 循环。使用结构化绑定(bind)(在 C++17 中再次可用),您可能会认为这更具可读性:

int result = 0;

for (const auto& [key, value] : f_table[1])
   result += value;

最后是基于 range-v3 的解决方案:

#include <range/v3/all.hpp>

using ranges::view::values;
using ranges::accumulate;

const int result = accumulate(f_table[1] | values, 0);

关于c++ - 遍历 unordered_map cpp 的 unordered_map 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52290200/

相关文章:

c++ - 如何在 C++ 中将函数作为参数传递

c++ DLNA 字幕显示实现与白金库

c++ - Linux C++ 编译错误

c++ - 无序映射会创建零初始化结构吗?

c++ - C++检查unordered_map/map的std::array包含相同的元素类型

c++ - C++11 是否支持 C11 的新特性?

c++ - C++ 映射的运算符重载

c++ - 如何从 const ref 获取键的值?

c++ - boost unordered_map 反向 foreach

c++ - C++17 中 std::unordered_map 的推导指南