Teererai Marange
Teererai Marange

Reputation: 2132

iterating through elements in unordered map of unordered_maps cpp

Suppose I have an unordered_map defined as below:

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;

And I wanted to sum up all elements in f_table[1] which should add up to 13. How would I go about it?

Upvotes: 0

Views: 182

Answers (2)

lubgr
lubgr

Reputation: 38267

One approach is using std::accumulate like this:

#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; });

Note that as @StoryTeller pointed out in the comments, you might want to prefer a parallel version of this algorithm, which will ship with fully conforming C++17 implementations, i.e., std::reduce.

Another option is a range based for loop. With structured bindings (again available in C++17), you might consider this more readable:

int result = 0;

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

And finally a solution based on range-v3:

#include <range/v3/all.hpp>

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

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

Upvotes: 7

JulianW
JulianW

Reputation: 907

int32_t sum = 0;
for (auto& p : f_table[1])
{
    sum += p.second
}

Upvotes: 1

Related Questions