9

So in C#, I have something similar to the following:

Dictionary<string, List<string>>

What's the most efficient way to do that in C++? I know c++ has 'map' and 'list' but I'm still in the pseudocode phase of writing this function, so I was wondering if something like this is even possible in C++. If so, how's the best way to make that equivalent data structure?

Thanks

Saif Ahsanullah
  • 204
  • 3
  • 13

2 Answers2

13

so I was wondering if something like this is even possible in C++

Yes. The STL features are variety of different containers: http://www.cplusplus.com/reference/stl/.

If so, how's the best way to make that equivalent data structure?

That depends on your requirements. For example std::vector vs std::list (see here for further information)

For a simple case I would just suggest you to use something like this:

#include <vector>
#include <map>
#include <string>

int main()
{
  std::map<std::string, std::vector<std::string>> map_of_strings;

  map_of_strings["a"] = { "1", "2", "3" };
  map_of_strings["b"] = { "4", "5", "6" };
  map_of_strings["c"] = { "7", "8", "9" };

  return 0;
}
Community
  • 1
  • 1
Lukas
  • 1,320
  • 12
  • 20
  • This will just be reading information from a file and then writing it to another file in an xml format. The key of the dictionary/map will be an outer node, while the list/vector located in the 'value' spot of that dictionary, will be the inner nodes. The problem is, that it may get pretty big so memory overhead will be an issue. The plus is, that once the dictionary is written, it won't need much alteration (adding, altering, etc.) other than writing to the xml in a simple nested loop (for every key in the dictionary, write all the list's values). – Saif Ahsanullah Apr 01 '16 at 20:28
6

You can use: map<string, vector<string>>. Map is closest to C# Dictionary, and Vector to C# List.

If we abstract away from any language, there are:

Resizable arrays - List in C#, Vector in C++

Collections / containers of Key Value pairs - Dictionary in C# and Map in C++

Bad
  • 4,967
  • 4
  • 34
  • 50