Does `std::set` sort elements in every case?

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


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...


Yes, std::set stores its elements in such a way that iterating over the elements will be done in sorted order (and the call to std::adjacent_find is to show that std::set stores unique items as well).

#include <algorithm>
#include <iterator>
#include <ios>
#include <iostream>
#include <set>
#include <string>

int main()
{
    auto const ss = std::set<std::string> { "foo", "bar", "test" };
    std::cout << std::boolalpha << std::is_sorted(begin(ss), end(ss)) << "\n";
    std::cout << std::boolalpha << (std::adjacent_find(begin(ss), end(ss)) == end(ss)) << "\n";
    std::copy(begin(ss), end(ss), std::ostream_iterator<std::string>(std::cout, "\n"));
}

Live Example