I am using Boost unordered_map. I have a key value pair for each entry. How could I determine whether a particular value exist in the map? (I don\'t want to create another u
How about the following:
typedef std::unordered_map<int,std::string> map_type;
typedef std::unordered_map<int,std::string>::value_type map_value_type;
map_type m;
if (m.end() != find_if(m.begin(),m.end(),[](const map_value_type& vt)
{ return vt.second == "abc"; }
))
std::cout << "Value found." << std::end;
else
std::cout << "Value NOT found." << std::end;
Or using an external variable that is captured:
std::string value = "abc";
if (m.end() != find_if(m.begin(),m.end(),[&value](const map_value_type& vt)
{ return vt.second == value; }))
std::cout << "Value found." << std::end;
else
std::cout << "Value NOT found." << std::end;
Why can't we use count method instead of find()
Description: Count elements with a specific key Searches the container for elements whose key is k and returns the number of elements found. Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.
unordered_map<int, int> hash;
//converted array into hashMap
for(int i=0; i<6; i++)
{
hash[i];
}
//commom elemenest value is set to 1 in hashMap
for(int i =0; i<7; i++)
{
//element exist in array1
if(hash.count(i))
{
hash[i] = 1;
}
}
Boost has the Bimap, which is a bidirectional map (ie, keys and values both refer to each other). This sounds more appropriate for your needs than the unordered_map
.
You need to iterate over all the elements in the unordered_map
and see if the given value exists.
The std::find_if
algorithm with a custom predicate can be used to simplify this.