-1

I want to create a static map of relations known in compilation time:

{
    {k11, v1}, {k12, v1}, {k13, v1}, ...
    {k21, v2}, {k22, v2}, {k23, v2}, ...
    ...
    {kn1, vn}, {kn2, vn}, {kn3, vn}, ...
}

This may include many key-value pairs per row, and so, I would much rather write it like:

{
    {v1, {k11, k12, k13, ...}},
    {v2, {k21, k22, k23, ...}},
    ...
    {vn, {kn1, kn2, kn3, ...}}
}

What is the easiest (most readable) way to achieve this?

Benny K
  • 868
  • 6
  • 18
  • This smells like homework, so you better show some effort. That said, the easiest way is to just do what is easiest to you. If that solution isn't good enough, then the easiest way isn't suitable to the problem. "easy" isn't really specific enough. – Ulrich Eckhardt Oct 23 '18 at 06:33
  • I'd like to see a place that hands out this type of homework assignments... I'm writing some code for my work and I try to make it as readable as possible. After writing 1000+ lines of such hard coded maps, I want to see if I can make it more concise. – Benny K Oct 23 '18 at 06:38
  • 2
    If you are looking to get your code reviewed, go to codereview.stackexchange.com – CinCout Oct 23 '18 at 07:08

1 Answers1

0

One solution I can think of is using the following function:

#include <vector>
#include <tuple>
#include <map>
template <typename TValue, typename TKey>
std::map<TKey, TValue> reverse_map(
        std::vector<std::tuple<TValue, std::vector<TKey> > > const & relations){

    std::map<TKey, TValue> res;
    for (auto const & value_keys : relations){
        for(auto const & key : std::get<1u>(value_keys))
            res[key] = std::get<0u>(value_keys);
    }
    return res;
}

I'm not sure how going through such a function affects the running time. I'd be happy to hear if anyone has insight into this, or better solutions.

Benny K
  • 868
  • 6
  • 18