Click here to Skip to main content
15,884,629 members
Articles / Programming Languages / C++
Tip/Trick

One Line Solution to a Common Map Search Paradigm

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

Introduction

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).

C++
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.

C++
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.

C++
// 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."

License

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


Written By
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 2:33
Farhad Reza10-Nov-16 2:33 
QuestionThanks for the tip Pin
Kochise4-Nov-16 5:48
Kochise4-Nov-16 5: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.