STL映射 - 插入或更新

Cod*_*kie 18 c++ stl

我有一个对象映射,我想更新映射到键的对象,或者创建一个新对象并插入到映射中.更新由另一个获取指向对象的指针的函数完成(void update(MyClass*obj))

在地图中"插入或更新"元素的最佳方法是什么?

Ter*_*fey 21

operator[]    

  • 如果要插入默认的`MyClass`对象,然后更新它,这可以产生优雅的代码.如果您需要插入非默认对象,或者不更新插入的值,Charles的解决方案可能更好. (3认同)

CB *_*ley 12

使用以下代码片段:

std::map<Key, Value>::iterator i = amap.find(key);

if (i == amap.end())
    amap.insert(std::make_pair(key, CreateFunction()));
else
    UpdateFunction(&(i->second));
Run Code Online (Sandbox Code Playgroud)

如果要测量可能提高性能的内容,可能需要使用它.lower_bound()来查找条目的位置,并在需要插入新对象的情况下将其用作插入的提示.

std::map<Key, Value>::iterator i = amap.lower_bound(key);

if (i == amap.end() || i->first != key)
    amap.insert(i, std::make_pair(key, CreateFunction()));
                                       // Might need to check and decrement i.
                                       // Only guaranteed to be amortized constant
                                       // time if insertion is immediately after
                                       // the hint position.
else
    UpdateFunction(&(i->second));
Run Code Online (Sandbox Code Playgroud)