std::map 索引和插入调用之间的差异
std::map 的索引重载运算符和 insert 方法调用有什么区别?
即:
some_map["x"] = 500;
vs.
some_map.insert(pair<std::string, int>("x", 500));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信 insert() 不会覆盖现有值,并且可以通过测试返回的迭代器/对值中的 bool 值来检查操作的结果。
对下标运算符 [] 的赋值只会覆盖那里的任何内容(如果插入一个条目 。
如果您不期望这种行为并且不适应它,则插入和 [] 运算符中的任何一个都可能会导致问题
例如 with insert:
和 with [] 运算符:
我认为这些是正确的,但还没有编译它们,所以可能有语法错误
I believe insert() will not overwrite an existing value, and the result of the operation can be checked by testing the bool value in the iterator/pair value returned
The assignment to the subscript operator [] just overwrites whatever's there (inserting an entry if there isn't one there already)
Either of the insert and [] operators can cause issues if you're not expecting that behaviour and don't accommodate for it.
Eg with insert:
and with [] operator:
I think those are correct, but haven't compiled them, so may have syntax errors
对于
map
,前一个(operator[]
)表达式将始终用新提供的值替换键值对的值部分。如果新的键值对尚不存在,则将插入该对。相反,如果映射中尚不存在包含所提供的键部分的键值对,则
insert
只会插入新的键值对。For a
map
, the former (operator[]
) expression will always replace the value part of the key-value pair with the new supplied value. A new key-value pair will be inserted if one doesn't already exist.In contrast,
insert
will only insert a new key-value pair if a key-value pair with the supplied key part does not already exist in the map.除了
map::operator[]
将替换现有值之外,operator[]
map::将创建并添加到地图< /strong> 在替换发生之前要替换的默认现有值(map::operator[]()
调用必须返回对某些内容的引用)。对于创建成本昂贵的项目,这可能是一个性能问题。请参阅 map::operator[] 和
map::insert
之间仔细选择”。 stackoverflow.com/amzn/click/com/0321334876" rel="noreferrer">Scott Meyers 的有效 STL。In addition to the fact that
map::operator[]
will replace an existing value is thatoperator[]
map::will create and add to the map a default existing value to replace before the replacement occurs (themap::operator[]()
call has to return a reference to something). For items that are expensive to create this could be a performance issue.See "Item 24: Choose carefully between
map::operator[]
andmap::insert
when efficiency is important" in Scott Meyers' Effective STL.insert方法插入到map中,而重载索引运算符如果在map中,则返回键为key_value的元素,如果不在map中,则将其插入。
The insert method inserts into the map, while the overloaded index operator will return the element with the key key_value if it is in the map, if it is not already in the map then it will insert it.
只是添加到 Michael Burr 的答案,这本书您应该寻找的是 Scott Meyer 的 <Effective STL>不是,因为 Michael 错误地链接了它。
(添加新kv时)
更新现有的 k 的 v)
Just to add to Michael Burr's answer, the book you should be looking for is Scott Meyer's <Effective STL> not the <Effective C++>, as Michael has linked it wrongly.
(when adding new k-v)
(updating existing k's v)