C++ does begin/end/rbegin/rend execute in constant time for std::set, std::map, etc?

喜夏-厌秋 提交于 2020-01-14 10:09:31

问题


For data types such as std::set and std::map where lookup occurs in logarithmic time, is the implementation required to maintain the begin and end iterators? Does accessing begin and end imply a lookup that could occur in logarithmic time?

I have always assumed that begin and end always occur in constant time, however I can't find any confirmation of this in Josuttis. Now that I'm working on something where I need to be anal about performance, I want to make sure to cover my bases.

Thanks


回答1:


They happen in constant time. I'm looking at page 466 of the ISO/IEC 14882:2003 standard:

Table 65 - Container Requiments

a.begin(); (constant complexity)

a.end(); (constant complexity)

Table 66 - Reversible Container Requirements

a.rbegin(); (constant complexity)

a.rend(); (constant complexity)




回答2:


Yes, according to http://www.cplusplus.com/reference/stl/, begin(), end() etc are all O(1).




回答3:


In the C++ standard, Table 65 in 23.1 (Container Requirements) lists begin() and end() as requiring constant time. If your implementation violates this, it isn't conforming.




回答4:


Just look at the code, here you can see the iterators in the std::map in the GNU libstdc++

std::map

you'll see that all end rend cend ... are all implemented in constant time.




回答5:


Be careful with hash_map though. begin() is not constant.




回答6:


For std::set

begin: constant, end: constant, rbegin: constant, rend: constant,

For std::map

they are also constant (all of them)

if you have any doubt, just check www.cplusplus.com



来源:https://stackoverflow.com/questions/83640/c-does-begin-end-rbegin-rend-execute-in-constant-time-for-stdset-stdmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!