65.9K
CodeProject is changing. Read more.
Home

One Line Solution to a Common Map Search Paradigm

starIconstarIconstarIconstarIconstarIcon

5.00/5 (6 votes)

Nov 4, 2016

CPOL
viewsIcon

11540

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