Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the std::set iteration order always ascending according to the C++ specification?

Tags:

c++

set

stl

Here http://www.cplusplus.com/reference/stl/set/ I read that std::set in C++ is "typically" implemented as a tree (red-black one?) and it is sorted.

I could not understand, does it mean that by specification iteration order of set is always ascending? Or is it only "usual implementation detail" and sometimes, some library/compiler may violate this convention?

like image 724
Rodion Gorkovenko Avatar asked Jan 12 '12 10:01

Rodion Gorkovenko


People also ask

Is set always sorted in C++?

What is Set in C++? As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container.

Does set store data ascending order?

What is a Set? In programming, a Set is used to store unique values of a list and also automatically providing an ordering to its elements. By default, the ordering is in ascending order.

Is std::map always sorted?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

Does set preserve order C++?

No, it does not.


1 Answers

Per the C++ standard, iteration over the elements in an std::set proceeds in sorted order as determined by std::less or by the optional comparison predicate template argument.

(Also per the C++ standard, insertion, lookup and deletion take at most O(lg n) time, so balanced search trees are currently the only viable implementation choice for std::set, even though the use of red-black trees is not mandated by the standard.)

like image 141
Fred Foo Avatar answered Sep 20 '22 13:09

Fred Foo