Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

One Line Solution to a Common Map Search Paradigm

0.00/5 (No votes)
3 Nov 2016 1  
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).

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here