The only way I have found to check for duplicates is by inserting and checking the std::pair.second
for false
, but the problem is that this still inserts something if the key is unused, whereas what I want is a map.contains(key);
function.
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
Potatoswatter's answer is all right, but I prefer to use find
or lower_bound
instead. lower_bound
is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.
map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) { // not found
// ...
my_map.insert(iter, make_pair(key, value)); // hinted insertion
} else {
// ... use iter->second here
}
value
may be skipped if insertion is unnecessary.
lower_bound
-based solution is overkill. I kind of just mentioned my answer "for completeness"; like I said, yours is perfectly adequate. :-)
insert
a priori. Actually, there is another difference if using a multimap
, the lower_bound
method inserts at the beginning of the equivalent range whereas the plain insert
method adds to the end of the range.
Your desideratum,map.contains(key)
, was scheduled for the draft standard C++2a and implemented in C++20. In 2017 it was implemented by gcc 9.2. It's also in clang.
Success story sharing
map::count
is implemented asfind(__x) == end() ? 0 : 1;
. Formultimap
the you may have a performance argument, but that's not OP's question and I still prefer elegance.has(k)
/contains(k)
like every other sane map class on the planet. Poor interface design. The find() approach is too verbose and thecount(k)
approach is definitely not at semantic parity withhas(k)
. For that matter neither isfind(k)
. Check out the view count on this question.