Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ keys-value container with variable keys count

Is there some well known container (in boost for example) which provides access to the same value using different keys of the same type. All keys are unique. Each value may have variable keys count.

Here is very naive implementation:

class multi_key_map
{
    std::unordered_map<std::string, std::string> flatMap;

public:
    multi_key_map(std::initializer_list<std::pair<std::vector<std::string>, std::string>> map)
    {
        for (auto& kvp : map)
        {
            for (auto&& key : kvp.first)
            {
                flatMap.emplace(std::move(key), kvp.second);
            }
        }
    }

    const std::string& operator[](std::string& key) const
    {
      return flatMap.at(key);
    }
};

const multi_key_map vals =
{ 
    { { "k1", "k2", "k3" }, "val1" },
    { { "k4", "k5" }, "val2" },
    { { "k6" }, "val3" }
};

assert(vals["k1"] == "val1");
assert(vals["k2"] == "val1");
assert(vals["k4"] == "val2");

But I don't want to reinvent the wheel. I looked at boost.multiindex but I cannot find the desirable simple solution with variable keys count. And it seems that boost.multiindex was developed for purposes other than mine.

like image 455
Dmitry Katkevich Avatar asked Jul 08 '26 21:07

Dmitry Katkevich


1 Answers

If the values are simple, or small types, inserting the same value for all of its keys, into a std::map or a std::multimap should work just fine.

For more complicated objects, or if there's some specific need for multiple keys to refer to the same distinct object, use a std::map or a std::multimap with std::shared_ptr<value_class> values, inserting the same std::shared_ptr for all of the object value's keys. In this manner, all of the keys will end up referencing the same instance of the object.

like image 59
Sam Varshavchik Avatar answered Jul 11 '26 12:07

Sam Varshavchik