2

I would like to have a data structure similar to std::map with multiple key levels. For example in this my_map :

(‘a’ , “a1”) ->  “value1”
(‘a’ , “a2”) ->  “value2”
(‘b’ , “b1”) ->  “value3”
(‘b’ , “b2”) ->  “value4”

The first level key values are chars: ['a' and 'b'] and the second key levels are std::string ("a1", etc) and the values are strings.

API requirements:

Adding elements using two key values. Retrieve elements by the first key: my_map.at_first_level('a'), this should return a map like:

"a1" -> “value1”
"a2" -> “value2”

Is this "multi-level map" data structure implemented in any of the C++ libraries?

motam79
  • 3,542
  • 5
  • 34
  • 60

2 Answers2

7

Have you considered a map of maps ?

std::map<char, std::map<std::string, std::string> myMap;
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
KostasRim
  • 2,053
  • 1
  • 16
  • 32
  • This will work, but if I have more than two levels, the syntax would be cumbersome. I was hoping that someone has implemented a multi-level map similar to Pandas multi-index in C++, where you can lookup values by level number and level key. – motam79 Jun 10 '18 at 16:09
  • @motam79 If you have multiple levels maybe you are not mapping the problem correctly ? Are you sure you are using the correct data structure for the problem ? – KostasRim Jun 10 '18 at 16:10
  • @motam79 Could you give an example of the syntax you would prefer in your question? – Galik Jun 10 '18 at 16:25
2

I'd suggest Boost MultiIndex with composite_key https://www.boost.org/doc/libs/1_67_0/libs/multi_index/doc/tutorial/key_extraction.html

Here's a recent example I gave using it:

sehe
  • 374,641
  • 47
  • 450
  • 633