How to check if std::map contains a key without doing insert?

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.

Checking for Existence of an Element in Associative Containers, It is also not obvious for beginners. Quoting a question from Stack Overflow [1]:. How to check if std::map contains a key without doing insert? std::map::count just tells if the given key exists in map or not. But what if we also want to access the value associated with the given key. For that map provides another member function i.e. std::map::find. Check if map contains a key using std::map::find. std::map provides a member function find() i.e. iterator find (const key_type& k);

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
}

How check if a given key exists in a Map, As map contains elements with unique key only. So, it will return 1 if key exists else 0. Suppose we have map of string & int i.e.. How to check if std::map contains a key without doing insert? (2) 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.

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

QMap Class, QMap<QString, int> map;. To insert a (key, value) pair into the map, you can use operator[]():. How to check if std::map contains a key without doing insert? 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.

std::map, Value to be copied to (or moved as) the inserted element. Member type value_type is the type of the elements in the container, defined in map as pair<​const  10) If nh is an empty node handle, does nothing and returns the end iterator.Otherwise, inserts the element owned by nh into the container, if the container doesn't already contain an element with a key equivalent to nh. key (), and returns the iterator pointing to the element with key equivalent to nh. key (regardless of whether the insert succeeded or failed).

map::insert - C++ Reference, A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: Input : Map : 1 -> 4, 2 -> 6, 4 -> 6 Check1 : 5,  If you replace all occurences of std::map<std::string, int, comparer> with std::map<std::string, int> it will sure work. – Michael Krelin - hacker Dec 4 '11 at 11:05 The problem I am having in my main application is that I have to check for duplicates in the map before adding a new pair.

Check if a key is present in a C++ map or unordered_map , Hint pointer does not force the insertion at specific position. This function returns the pointer to the position where pair is inserted. Time complexity : log(n) where n​  I have a map of objects and I want to update the object mapped to a key, or create a new object and insert into the map. The update is done by a different function that takes a pointer to the object

Comments
  • possible duplicate of How to find if a given key exists in a C++ std::map
  • -1: Should use find. It is at least as efficient as count for maps and multimaps, and more efficient when you consider the typical need to make changes to the found keys.
  • @John: That reeks of premature optimization. On GCC (and I'm sure most reasonable systems), map::count is implemented as find(__x) == end() ? 0 : 1;. For multimap the you may have a performance argument, but that's not OP's question and I still prefer elegance.
  • No, the premature optimization argument is only valid if the optimization takes some effort which in this case it does not.
  • Not true. It's not premature if it makes the code easier to read or eliminates unnecessary overhead. In this case, if count() is implemented via find() anyway, then calling find() directly eliminates a function call... ergo, it's mature optimization. I find that using the find() call is more obvious, as well, but that's purely personal preference.
  • It is not a premature optimization to be aware of the perf of library functions before you make a habit of using them. In this case, you're right, it doesn't matter, but neither does the minuscule stylistic difference between find and count. I think you take the 'premature optimization' rhetoric too far. You should take any "free" optimization habits you can find and use them for everyday development. It's when coders succumb to the trap of paying costs in readability/dev time/etc, all for unmeasured "performance gains" that the premature optimization rhetoric becomes the right advice to give.
  • 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.
  • 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. :-)
  • 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.
  • Not the answer to the question, but my poor question asking lead me to the right answer here... I need to do the insert/update. :D
  • @Hunter Can you show me your code? If it's not massive, I can probably review it for you.
  • This is a nice feature! I think it has landed on C++20. cppreference.com