Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `std::set` sort elements in every case? [duplicate]

From cplusplus.com reference it seems that std::set sorts elements.

I need to have sorted strings, but I'm not sure if it will work well on every platform and compiler. Mainly GCC, MinGW, VC.

like image 239
kravemir Avatar asked Aug 04 '12 13:08

kravemir


2 Answers

By its definition std::set is a sorted container. Its part of the standard. Having it sorted helps maintain that its a set rather than just an arbitrary collection.

Source: http://www.sgi.com/tech/stl/set.html

like image 139
Daniel A. White Avatar answered Oct 15 '22 07:10

Daniel A. White


Actualy std::set and std::map are not really sorted. Both of these containers are implemented as a red-black trees. So when you iterate such kind of containers, iterator walks through the tree in such way that it looks like that container is sorted. At first it visits the most left node then the parent of the most left one and so on...

like image 21
Sergey Vystoropskyi Avatar answered Oct 15 '22 05:10

Sergey Vystoropskyi