learner
learner

Reputation: 127

How to find the value for a key in unordered map?

I am trying to do the below sample in unordered map in c++

my_dict = {'one': ['alpha','gamma'], 'two': ['beta'], 'three' : ['charlie']}
print(my_dict["one"]) // ['alpha','gamma']

I tried using find operator like below

int main ()
{
std::unordered_map<std::string, std::vector<std::string>> dict;
dict["one"].push_back("alpha");
dict["one"].push_back("beta");
dict["two"].push_back("gamma");
 auto it = dict.find("one");
 cout<<it->second<<endl; // expected output alphabeta
return 0;
}

But I am not able to retrieve the value for this key dict["one"]. Am i missing anything ? Any help is highly appreciated. Thanks

Upvotes: 2

Views: 6841

Answers (2)

Bitwize
Bitwize

Reputation: 11220

The failure you are encountering is due to it->second being a std::vector object, which cannot be printed to std::cout because it lacks an overload for operator<<(std::ostream&,...).

Unlike languages like Python that do this for you, in C++ you must manually loop through the elements and print each entry.

To fix this, you will need to change this line:

 cout<<it->second<<endl; // expected output alphabeta

To instead print each object in the container. This could be something simple like looping through all elements and printing them:

for (const auto& v : it->second) {
    std::cout << v << ' '; // Note: this will leave an extra space at the end
}
std::cout << std::endl;

Or you can go more complex if the exact formatting is important.


@DanielLangr posted a link in the comments to the question that summarizes all possible ways of doing this, and I recommend taking a look if you're wanting anything more complex: How do I print the contents to a Vector?

Upvotes: 2

Unyaya
Unyaya

Reputation: 66

This is because your it->first will point to the key of the dictionary i.e. "One" and it->second will point to the value i.e. the vector.

So to print elements of the vector you need to specify the indexes of the vector that you are printing as well. The following code will give you the result you want:

int main() {
std::unordered_map <std::string, std::vector<std::string>> dict;
dict["one"].push_back("alpha");
dict["one"].push_back("beta");
dict["two"].push_back("gamma");
auto it = dict.find("one");
cout<<it->second[0]<<it->second[1]<<endl; // expected output alphabeta
return 0;

}

P.S. Please accept my answer if you find it useful as that would help me get some reputation points

Upvotes: 1

Related Questions