user313
user313

Reputation: 699

How to store/access multiple values of the same key in a map C++

So lets say I declare an unordered_map like this:

unordered_map<string, vector<string>> my_map;

And I have a list of values I want to store in it like this:

vector<string> vec1 = {"banana", "apple"}; 
vector<string> vec2 = {"banana", "banana"};
vector<string> vec3 = {"banana", "watermelon"};

if I go through and initialize each vector to the map, using the string in its 0th index as the key, like so:

my_map[vec1[0]] = vec1;
my_map[vec2[0]] = vec2;
my_map[vec3[0]] = vec3;

Would the unordered_map store all three of the vectors despite them having the same access key? And if I wanted to access each vector, is there a way I could do so in the same order that they appear in the list above?

So for example, if I did this:

 vector<string> output1;
 vector<string> output2;
 vector<string> output3;

 output1 = my_map["banana"];
 output2 = my_map["banana"];
 output3 = my_map["banana"];

which vectors would be assigned to output1, output2 and output3? I'm pretty sure it would be the same vector for all but how does unordered_map decide which one? And how can I make it so vec1 would be assigned to output1, vec2 to output2, etc?

Upvotes: 2

Views: 4608

Answers (2)

Ragav
Ragav

Reputation: 325

If 2 elements have the same key then the first key value will be printed , others are ignored.

So Try the Map of Map:

Sample Snippet :

  std::multimap <int, xxx> stdBindListOuter;
  std::multimap <int, std::string>::iterator pos;
  std::multimap <int, xxx>::iterator posOuter;

xxx--> can be user-defined..

So more flexible to use this type of versions for your case. rather than Ordered or unordered map..

Upvotes: 1

Anton Savin
Anton Savin

Reputation: 41301

std::unordered_map stores only one value for each key - the last you assigned to it, in your case it's vec3. If you want to store several values for each key you can use std::multimap or std::unordered_multimap.

Upvotes: 7

Related Questions