Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

like image 506
Doug T. Avatar asked Sep 17 '08 14:09

Doug T.


People also ask

What is Rbegin and rend in C++?

vector rbegin() and rend() function in C++ STL Return value: The function returns a reverse iterator pointing to the last element in the container.

How does rbegin work c++?

The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.

How do you find the last element on a map?

map::end() end() function is used to return an iterator pointing to past the last element of the map container.


2 Answers

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)

like image 186
nsanders Avatar answered Oct 18 '22 21:10

nsanders


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

like image 34
benefactual Avatar answered Oct 18 '22 20:10

benefactual