Recently I had been learning maps in C and I came across various problems where I need to check if a "KEY" exists for a given value. In JAVA we can do so by following code snippet -
hash_map.containsValue(VALUE); // Returns true if there is a key for the value, as false
I am looking for similar stuff in C . I have found resources that can check for existing of "KEY" like :
mp.count(k); //will return 0 if a key "k" not exists, else it's count
But how to do it for "VALUE NOT KEY"?
CodePudding user response:
A clean way is to loop over the map with a structured binding (since c 17):
std::map<int, int> map;
for (const auto& [k, v] : map) {
if (v == VALUE) {
std::cout << "found value\n";
}
}
I also recommend using std::find_if
and checking if the returned found iterator is valid:
auto it = std::find_if(map.cbegin(), map.cend(), [&](const auto& entry) {
return entry.second == VALUE;
});
if (it != map.cend()) {
std::cout << "found value\n";
}
CodePudding user response:
In C there is no such direct method to check if a given map contains the value. One will have to iterate through the entire map and check if it contains the value or note. It can be achieved as follows
std::map<int,int> m;
//let's assume that map is already filled.
for(const auto& i:m){
if(i.second==value)
return true;
}
return false;
Hope it helps.
CodePudding user response:
Late to the game, but with a full example (somewhat templated):
#include <iostream>
#include <map>
#include <string>
template<typename K, typename V>
bool containsValue(const std::map<K,V>& m, const V& v)
{
for (const auto& x: m) {
if (x.second == v) {
return true;
}
}
return false;
}
int main()
{
using namespace std::string_literals;
std::map<std::string, std::string> mp = {
{"Jones", "James"},
{"Smith", "Mary"},
{"Garcia", "Robert"},
{"Edwards", "Patricia"},
{"Brown", "John"},
{"Thompson", "Jennifer"},
{"Sullivan", "Michael"},
{"Rodriguez", "Linda"},
{"Williams", "David"},
{"Johnson", "Elizabeth"},
};
std::cout << std::boolalpha;
std::cout << containsValue(mp, "Patricia"s) << '\n';
std::cout << containsValue(mp, "Jack"s) << '\n';
return 0;
}
This is not ideal, because it's really specific for std::map
and it's sad that I cannot pass a string literal without the final s
specifier. I'm sure someone knows how to improve the templated function.