0

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?

7
  • 1
    An unordererd map seems like the wrong tool here. Why not use std::array<std::array<int, 3>, 3> and zero-index? Commented Sep 12, 2018 at 7:59
  • Do you know how to iterate over any other container? Do you know what the value type of a std::unordered_map? When you know that it should become easy. Commented Sep 12, 2018 at 7:59
  • Because I dont know how large it will get. Commented Sep 12, 2018 at 8:02
  • 2
    sum = 0, for(auto& pair : f_table[1]) sum += pair.second; you might want to check if f_table[1] exists first. Commented Sep 12, 2018 at 8:02
  • How about using vectors then? Or will the "indexes" ever be non-consecutive? Commented Sep 12, 2018 at 8:04

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

4 Comments

If we mention C++17, then std::accumulate can be substituted for the paralleled version of std::reduce
That's a good idea, but is it available? Doesn't seem to be supported according to this.
Doesn't matter. Answers are not only for the benefit of the OP now, but for future readers too.
Well, it does matter, if the solution doesn't work. There may be some value if it could work in 10 years' time but then post it in 10 years time
1
int32_t sum = 0;
for (auto& p : f_table[1])
{
    sum += p.second
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.