-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?

3
  • 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. Commented Oct 23, 2018 at 6: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. Commented Oct 23, 2018 at 6:38
  • 2
    If you are looking to get your code reviewed, go to codereview.stackexchange.com Commented Oct 23, 2018 at 7:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.