Quantcast
Channel: How to find if a given key exists in a std::map - Stack Overflow
Viewing all articles
Browse latest Browse all 16

Answer by Lambage for How to find if a given key exists in a std::map

$
0
0
template <typename T, typename Key>bool key_exists(const T& container, const Key& key){    return (container.find(key) != std::end(container));}

Of course if you wanted to get fancier you could always template out a function that also took a found function and a not found function, something like this:

template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction>void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function){    auto& it = container.find(key);    if (it != std::end(container))    {        found_function(key, it->second);    }    else    {        not_found_function(key);    }}

And use it like this:

    std::map<int, int> some_map;    find_and_execute(some_map, 1,        [](int key, int value){ std::cout << "key "<< key << " found, value: "<< value << std::endl; },        [](int key){ std::cout << "key "<< key << " not found"<< std::endl; });

The downside to this is coming up with a good name, "find_and_execute" is awkward and I can't come up with anything better off the top of my head...


Viewing all articles
Browse latest Browse all 16

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>