快速访问 std::map 的元素
您知道当我使用 find
或 operator []
访问 std::map
元素时,性能是否有任何差异?
一个返回一个iterator
,另一个返回一个对象的const ref
。
由于 STL 的所有幕后工作,哪一个可能更快?
Do you know if it is any difference in performance when I access a std::map
element using find
or operator []
?
One returns an iterator
and the other a const ref
to the object.
Which one might be quicker becuase of all of the behind the scene of the STL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在不存在的键上使用 [] 时,将插入默认元素。此默认元素取决于您的映射定义(例如,对于 int 它将为零)。
当您使用 find 时,没有“自动”插入,因此如果您经常搜索不存在的键,速度会相当快。
When you use [] on a key that doesn't exist, the default element will be inserted. This default element depends on your map definition (for example, for an int it will be a zero).
When you use find, there is no "automatic" insertion, so it can be quite faster if you often search for keys that does not exist.
find() 的时间复杂度为 O(n)。
运算符 []
的复杂度为 O(1)。因此后者(通常)更快。find()
is O(n).operator []
is O(1). Therefore the latter is (usually) faster.