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 NutCracker for How to find if a given key exists in a std::map

$
0
0

I know this question already has some good answers but I think my solution is worth of sharing.

It works for both std::map and std::vector<std::pair<T, U>> and is available from C++11.

template <typename ForwardIterator, typename Key>bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) {    using ValueType = typename std::iterator_traits<ForwardIterator>::value_type;    auto search_result = std::find_if(        first, last,        [&key](ValueType const& item) {            return item.first == key;        }    );    if (search_result == last) {        return false;    } else {        return true;    }}

Viewing all articles
Browse latest Browse all 16

Trending Articles



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