So I am doing this:
if (mp.find(3) == mp.end()) {
cout << "3 value is there";
but it gives right for both when there is a 3 key and/or a 3 value. I just want it to return true when there is a 3 value
So I am doing this:
if (mp.find(3) == mp.end()) {
cout << "3 value is there";
but it gives right for both when there is a 3 key and/or a 3 value. I just want it to return true when there is a 3 value
Per the std::unordered_map
documentation, find
is looking for a key in the map. Fortunately, it's pretty simple to iterate over the pairs in a map to see if a specific value is present.
template <typename K, typename V>
bool has_value(std::unordered_map<K, V> &map, V val) {
for (auto &[k, v] : map) {
if (v == val) return true;
}
return false;
}
And then using that function:
int main() {
std::unordered_map<int, int> map = {
{14, 3},
{56, 2},
{17, 8}
};
std::cout << has_value(map, 2) << std::endl;
return 0;
}
This will print 1
.