快速访问 std::map 的元素

发布于 2024-09-11 06:34:40 字数 201 浏览 2 评论 0原文

您知道当我使用 findoperator [] 访问 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的背包 2024-09-18 06:34:40

当您在不存在的键上使用 [] 时,将插入默认元素。此默认元素取决于您的映射定义(例如,对于 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.

鹊巢 2024-09-18 06:34:40

find() 的时间复杂度为 O(n)。 运算符 [] 的复杂度为 O(1)。因此后者(通常)更快。

find() is O(n). operator [] is O(1). Therefore the latter is (usually) faster.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文