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.
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.
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.
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"));
}
C++11 N3337 standard draft 23.2.4 "Associative containers":
1 Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set, multiset, map and multimap.
and:
10 The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them.
so yes, order is guaranteed, which as https://stackoverflow.com/a/11812871/895245 mentioned basically requires a balanced search tree implementation.
Also contrast with C++11 unordered_set
, which may provide better performance since it has less restrictions: Why on earth would anyone use set instead of unordered_set? e.g. using a hash set.