user1899020
user1899020

Reputation: 13575

How to insert elements in a map efficiently?

How to insert elements in a std::map efficiently? A common requirement is that if the map already has the element key, return false; otherwise insert it and return true. I cannot find a good ready method to do it.

template<class Key, class Value>
bool insert(Key const& key, Value const& value, std::map<Key, Value>& myMap);

Upvotes: 0

Views: 157

Answers (2)

Nildram
Nildram

Reputation: 361

Following on from Daniels answer, may I suggest using insert() rather than emplace() and provide a separate emplace() method on your class if you need it?

The reason is that emplace() makes explicit constructors implicit. This means that if Value is non-copyable you will need to either use map.insert or ensure that Value provides a move assignment operator. The insert() also maintains backwards compatibility with pre C++11 compilers (if that is likely to be an issue).

template<class Key, class Value>
bool insert(Key const& key, Value const& value, std::map<Key, Value>& myMap)
{
    return myMap.insert(std::make_pair(key,value)).second;
}

template<class Key, class Value>
bool emplace(Key const& key, Value const& value, std::map<Key, Value>& myMap)
{
    return myMap.emplace(key,value).second;
}

Upvotes: 1

Daniel Frey
Daniel Frey

Reputation: 56863

How about using std::map::emplace:

template<class Key, class Value>
bool insert(Key const& key, Value const& value, std::map<Key, Value>& myMap)
{
    return myMap.emplace(key,value).second;
}

In case it's not available in your environment, you can use

template<class Key, class Value>
bool insert(Key const& key, Value const& value, std::map<Key, Value>& myMap)
{
    typedef typename std::map<Key, Value>::value_type value_type;
    return myMap.insert(value_type(key,value)).second;
}

Upvotes: 4

Related Questions