简体   繁体   中英

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?

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.

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

You can write objmap[key] = value .

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

 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM