简体   繁体   English

使用 at() 访问 std::map 元素是否比 operator[] 慢?

[英]Is it slower to access std::map elements with at() than operator[]?

When I want get certain element from a std::map , as far as I know at() will do a bounds check.当我想从std::map获取某些元素时,据我所知at()将进行边界检查。 Does that mean it's slower than [] ?这是否意味着它比[]慢?

Both std::map::at and std::map::operator[] check presence of key. std::map::atstd::map::operator[]检查密钥的存在。 Former throws exception when not found, later creates default value.前者在找不到时抛出异常,后来创建默认值。

Their complexity is mandatory to be log(n) (look-up).它们的复杂性必须是log(n) (查找)。 Performance by itself is not mandatory to be identical, but should be similar in practice.性能本身并不一定要相同,但在实践中应该相似。

So choose the one to use from their behavior (after the look-up).因此,从他们的行为中选择要使用的(在查找之后)。 Similar alternatives might be map::find or in some cases map::insert / insert_or_assign / emplace .类似的替代方案可能是map::find或在某些情况下map::insert / insert_or_assign / emplace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM