前段时间,我和同事讨论了如何在STL映射中插入值。I prefer map[key] = value;因为它让人感觉自然,读起来清晰,而他更喜欢地图。插入(std:: make_pair(关键字,值))。

我只是问了他,我们都不记得为什么插入更好,但我相信这不仅仅是一个风格偏好,而是有一个技术原因,如效率。SGI STL引用简单地说:“严格地说,这个成员函数是不必要的:它只是为了方便而存在。”

有人能告诉我原因吗,还是我只是在做梦?


当前回答

现在在c++11中,我认为在STL映射中插入一对的最好方法是:

typedef std::map<int, std::string> MyMap;
MyMap map;

auto& result = map.emplace(3,"Hello");

结果将是一对:

第一个元素(result.first),指向插入或指向的对 如果密钥已经存在,则使用此密钥对。 第二个元素(result.second),如果插入正确则为true 假装出了什么差错。

PS:如果你不关心顺序,你可以使用std::unordered_map;)

谢谢!

其他回答

insert()和operator[]之间的区别已经在其他答案中很好地解释了。然而,c++ 11和c++ 17分别引入了新的std::map插入方法:

c++ 11提供了emplace(),在einpoklum的评论和GutiMac的回答中也提到过。 c++ 17提供了insert_or_assign()和try_emplace()。

让我简单总结一下“新”插入方法:

emplace(): When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert(), an element is only inserted if there is no element with the same key in the container. insert_or_assign(): This method is an "improved" version of operator[]. Unlike operator[], insert_or_assign() doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer. try_emplace(): This method is an "improved" version of emplace(). Unlike emplace(), try_emplace() doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.

有关insert_or_assign()和try_emplace()的更多详细信息,请在这里看到我的回答。

Coliru上的简单示例代码

当涉及到映射中已经存在的键时,两者具有不同的语义。所以它们没有直接的可比性。

但是操作符[]版本需要默认构造值,然后赋值,所以如果这比复制构造更昂贵,那么它也会更昂贵。有时默认结构没有意义,那么就不可能使用操作符[]版本。

当你写作的时候

map[key] = value;

没有办法知道你是否替换了value for key,或者你是否用value创建了一个新键。

Map::insert()只创建:

using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
    cout << "key " <<  key << " already exists "
         << " with value " << (res.first)->second << endl;
} else {
    cout << "created key " << key << " with value " << value << endl;
}

对于我的大多数应用程序,我通常不关心我是在创建还是替换,所以我使用更容易阅读的map[key] = value。

map::insert()的一个问题是,如果键已经存在于映射中,它不会替换某个值。我见过Java程序员编写的c++代码,他们希望insert()的行为与Java中的Map.put()相同,其中值被替换。

从异常安全的角度来看,Insert更好。

表达式map[key] = value实际上是两个操作:

Map [key] -创建一个默认值的Map元素。 = value—将值复制到该元素中。

第二步可能发生异常。因此,该操作将只完成部分(一个新元素被添加到map中,但该元素没有初始化值)。当一个操作没有完成,但系统状态被修改时,这种情况被称为有“副作用”的操作。

插入操作提供了强有力的保证,意味着它没有副作用(https://en.wikipedia.org/wiki/Exception_safety)。插入要么完全完成,要么使映射处于未修改状态。

http://www.cplusplus.com/reference/map/map/insert/:

如果要插入单个元素,则在异常情况下容器中不会有任何更改(强保证)。