steveoreo
steveoreo

Reputation: 81

how check if std::map key exists for object's property update otherwise insert a new one?

in java, I sometimes do this

Map<String, POJO> objmap = new HashMap<String, POJO>();
POJO obj = null;
if ((obj = objMap.get(key)) == null) {
    obj = new POJO();
    objMap.put(key, obj);
}
obj.setName("something");
obj.setAddress("yeah");

What is the best practice to do similar thing in c++ with std::map? to create a obj in map if not exist, then update its properties?

Upvotes: 1

Views: 2041

Answers (5)

Andrew Komiagin
Andrew Komiagin

Reputation: 6556

the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element

    if ( !myMap.insert( std::make_pair( key, value ) ).second ) 
    {
        //  Element already present...
    }

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477070

Like this:

void insert_or_update(const K & k, const T & t, std::map<K, T> & m)
{
    auto p = m.insert(std::make_pair(k, t));
    if (!p.second) p.first->second = t;
}

Or:

    m[k] = t;

The latter requires T to be default-constructible and assignable.

In C++17 you can also say:

m.insert_or_assign(k, t);

This has fewer restrictions than the above construction and returns information on whether the insertion took place, as well as the iterator to the element.

Upvotes: 3

Vincent Ho
Vincent Ho

Reputation: 116

 std::map<std::string, POJO> mapStr2Pojo;
 mapStr2Pojo["something"].setName("something");
 mapStr2Pojo["something"].setAddress("yeah");

std::map<>'s operation[] inserts the object if it doesn't find it.

Upvotes: 0

therainmaker
therainmaker

Reputation: 4343

You can write objmap[key] = value.

See: http://www.cplusplus.com/reference/map/map/operator[]/

Upvotes: 1

Alon
Alon

Reputation: 1804

You want to use the insert function, it returns an iterator and a boolean regarding whether a new object was inserted: something like this:

typedef map<int,void*> M;
M m;
auto insertion = m.insert(M::value_type(0,nullptr));
if (insertion.second) {
insertion.first->second = new... (// allocate your item or whatever, this is the iterator to it)
}

Upvotes: 1

Related Questions