Reputation: 5684
I am trying to access the value of particular hash key. The example code is below. Test Here
// unordered_map::at
#include <iostream>
#include <string>
#include <unordered_map>
int main ()
{
std::unordered_map<std::string,int> hashmap = {
{ "Apple", 300},
{ "Banana", 60},
{ "Orange", 70 } };
std::cout << "Value :" << hashmap[300]<<std::endl;
return 0;
}
However when I try to access key of a particular value, it works fine, like hashmap["Apple"]
, it give 300
i,e the key of Apple
. How to make it work otherwise like hashmap[300]
to give "Apple" .
Upvotes: 1
Views: 6925
Reputation: 12751
There is no direct access as you expected.
One of the ways is to use std::find_if
.
//DATA
std::unordered_map<std::string,int> hashmap = {
{"Apple", 300},
{"Banana",60},
{"Orange",70}
};
//FIND BASED ON GIVEN INPUT
const auto& foundItem = std::find_if(hashmap.begin(),hashmap.end(),
[](const std::pair<std::string,int>& item)
{
return item.second == 300;
});
std::cout<<foundItem->first<<std::endl;
And moreover, when you are looking for value in a unordered map, there is a possibility of another key having similar value.
for example another element {"grape",300}
. If you want all the keys with value 300....
//DATA
std::unordered_map<std::string,int> hashmap = {
{"Apple", 300},
{"Banana",60},
{"Orange",70},
{"Grape",300}
};
//RESULT
std::vector<std::string> foundValues;
//FIND BASED ON GIVEN INPUT
std::for_each(hashmap.begin(),hashmap.end(),
[&foundValues](const std::pair<std::string,int>& item)
{
if(item.second == 300)
foundValues.push_back(item.first);
});
//JUST TO TEST
std::cout<<foundValues[0]<<" "<<foundValues[1]<<std::endl;
Upvotes: 0
Reputation: 303087
How to make it work otherwise like
hashmap[300]
to give"Apple"
.
Hash maps are unidirectional: key --> value
. If you need both directions to be fast, you'll need a different data structure (like Boost.Bimap).
If you just want that lookup to work period and are okay with linear performance, than you can just use std::find_if
:
auto it = std::find_if(hashmap.begin(), hashmap.end(),
[](auto const& pr){ return pr.second == 300; });
if (it != hashmap.end()) {
std::cout << "Key for 300: " << it->first;
}
There's nothing in std::unordered_map
that based on looking up values.
Upvotes: 3