std :: map insert()提示位置:c ++ 98和c ++之间的区别11 [英] std::map insert() hint location: difference between c++98 and c++11

查看:188
本文介绍了std :: map insert()提示位置:c ++ 98和c ++之间的区别11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cplusplus'在地图上的条目:: insert()我阅读了一个可能的位置添加为函数优化其插入时间(如果 position )指向先于插入元素c的元素的提示++ 98,而对于c ++ 11,优化发生如果 position 指向将跟随插入元素(或结束,如果它是最后一个)。

On cplusplus' entry on map::insert() I read about the location one could add as a hint for the function that the "function optimizes its insertion time if position points to the element that will precede the inserted element" for c++98, while for c++11 the optimization occurs "if position points to the element that will follow the inserted element (or to the end, if it would be the last)".

这是否意味着以下表单的代码片段的性能(在我遗留的代码中是丰富的在 Scott Meyer 的Effective STL(项目24))上工作和建模,在切换到符合C ++ 11编译器?

Does this mean that the performance of code snippets of the following form (which are abundant in the legacy code I'm working on and modeled after Scott Meyer's "Effective STL", item 24) were affected in switching to a C++11-compliant compiler?

auto pLoc = someMap.lower_bound(someKey);
if(pLoc != someMap.end() && !(someMap.key_comp()(someKey, pLoc->first)))
    return pLoc->second;
else
    auto newValue = expensiveCalculation();
    someMap.insert(pLoc, make_pair(someKey, newValue));  // using the lower bound as hint
    return newValue;

什么是改进此模式以用于C ++ 11的最佳方法?

What would be the best way to improve this pattern for use with C++11?

推荐答案

C ++ 98规范是标准中的一个缺陷。请参阅 LWG问题233 N1780 中的讨论。

The C++98 specification is a defect in the standard. See the discussion in LWG issue 233 and N1780.

回想一下, lower_bound 将键值不小于指定键的第一个元素返回一个迭代器,而 upper_bound 将返回一个迭代器到键大于指定键的第一个元素。如果没有与容器中的指定键相等的键,则 lower_bound upper_bound 返回相同的事情 - 迭代器到之后的元素,如果它在地图中。

Recall that lower_bound returns an iterator to the first element with key not less than the specified key, while upper_bound returns an iterator to the first element with key greater than the specified key. If there is no key equivalent to the specified key in the container, then lower_bound and upper_bound return the same thing - an iterator to the element that would be after the key if it were in the map.

所以,换句话说,你当前的代码已经工作正确的C ++ 11规范,实际上是错误的C ++ 98的缺陷规范。

So, in other words, your current code already works correctly under the C++11 spec, and in fact would be wrong under C++98's defective specification.

这篇关于std :: map insert()提示位置:c ++ 98和c ++之间的区别11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆