Click here to Skip to main content
14,362,338 members

One Line Solution to a Common Map Search Paradigm

Rate this:
5.00 (6 votes)
Please Sign up or sign in to vote.
5.00 (6 votes)
3 Nov 2016CPOL
There is an efficient way provided by std::map to solve a common programming pattern ("query-and-insert-if-nonexistent")


This is a really quick tip. std::map provides an efficient way to write code for the common paradigm: "query-and-insert-if-doesn't-exist".

If you have been using std::map, one common paradigm you may encounter is: (believe me, you probably already have, even if you didn't realize).

using CMyMap = std::map<std::string, int>;

// Return true only if a new item is inserted; If the item exists, return false.
bool InsertNewItem(const CMyMap &thisMap, const string &key, int value)
    bool alreadyExisted = false;
    if (thisMap.find(key) != thisMap.end()) {
        alreadyExisted = true
    else {
        thisMap[key] = value;
    return !alreadyExisted;

The thing is, you can't simply run the following line because otherwise you can't tell if the value is newly inserted.

thisMap[key] = value;

But the code above seems a bit messy for such a simple task, a very common one. Thanks to the designers of STL, this has been considered. std::map() already provides an overloaded version of insert() member function to solve it.

// std::map
// pair<iterator,bool> insert (const value_type& val);

// Return true only if a new item is inserted; If the item exists, return false.
bool InsertNewItem(const CMyMap &thisMap, const string &key, int value)
    std::pair<CMyMap::iterator, bool> res = thisMap.insert(CMyMap::value_type(key, value));
    return res.second;

The map::insert() function returns a std::pair. The first member of this pair is an iterator. It always points to the item in map, whether it's newly created or not. The second member is a bool value, denoting if key is found before insertion. So it basically implements the semantics we need: "Tell me if this key exists in map, and insert into it if not."


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Eric Z (Jing)
Technical Lead National Instruments
China China
Senior software engineer at National Instruments, to implement various Ethernet-based industrial protocols, e.g., EtherCAT. Favorite languages are C/C++ and Python. For fun, I like watching films (sci-fi, motion), walking, and various reading.

Comments and Discussions

GeneralMy vote of 5 Pin
Farhad Reza10-Nov-16 3:33
memberFarhad Reza10-Nov-16 3:33 
QuestionThanks for the tip Pin
Kochise4-Nov-16 6:48
memberKochise4-Nov-16 6:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 3 Nov 2016

Tagged as