tags:

views:

108

answers:

3

The only way I have found to check for duplicates is by inserting and checking the std::par.second for false, but the problem is that still inserts something if the key is unused whereas I more want is as a map.contains(key); function.

Thanks

+9  A: 

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
+6  A: 

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
}
Chris Jester-Young
This is subtly different from how he says he's doing it… the only difference is that computation of `value` may be skipped if insertion is unnecessary.
Potatoswatter
Sure, I understand that the OP doesn't care to insert, so a `lower_bound`-based solution is overkill. I kind of just mentioned my answer "for completeness"; like I said, yours is perfectly adequate. :-)
Chris Jester-Young
Yep, this is a good answer and I don't disagree with anything. Just pointing out the relationship to the alternative of `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.
Potatoswatter
+1 This additional answer was educational
Greg Domjan
A: 

If you happen to use Qt, you might use the QMap class. It basically behaves like std::map, but also has a contains()-function.

Sebastian N.
and is non-standard :(
Inverse