mercredi 4 novembre 2015

How iterating over a std::set returns sorted results

The container std::set (or std::map) is a data structure that STL provides. In almost all compilers it is implemented as a R&B tree with guaranteed log(n) insertion, find and removal time.

http://ift.tt/1ooIUdP

In a red and black tree the elements are sorted based on the "less" operator of the stored element. So basically if a root is N + 1 , N will be on the left sub-tree while N + 2 will be on the right sub-tree and this will be decided by the less operator.

My question is when executing the below code:

 set<unsigned long>::iterator it;
 for (it = myset.begin(); it != myset.end(); it++) {
     cout << *it;
 }

the elements are returned in a sorted order. How can this be possible considering the fact that the underlying data structure is a red and black tree? Is there a separate linked list stored to be able to iterate from the leftmost sub-tree to rightmost sub-tree? If not what is the mechanism behind this implementation using a R&B tree?

Aucun commentaire:

Enregistrer un commentaire