I know that people use unordered_set
when they don't care about the order of the elements in the set. However, when I run the sample program on C++ Shell
#include <iostream>
#include <unordered_set>
#include <string>
int main()
{
std::unordered_set<std::string> inputSet;
inputSet.insert("Hello world");
inputSet.insert("Abcdef");
inputSet.insert("This is the test string...");
for(const auto &val : inputSet)
std::cout << val.c_str() << std::endl;
return 0;}
it gives me
This is the test string...
Abcdef
Hello world
And I tried to run it for 3 or 4 times, it still gives me the same output which implies that there is a way that unordered_set
determine the inserting order.
Can someone explain how does unordered_set
determine the inserting order?
Sorry if it has been asked before, I've searched online for a while and I cannot find a specific answer to this question. Thanks in advance.
There is no specific ordering... It uses the default
std::hash
to hash the string. And whatever the hash value is, it is converted into an appropriate bucket index in the container..The hash value we are talking about can be gotten:
For a particular STL implementation, this resolves to:
See it Live on C++Shell
The value is usually converted to an appropriate bucket index by applying
%
operator. Again thestd::unordered_set
's iterator isn't mandated to sequentially iterate through all the buckets (what about collisions?). So, you should not rely on any ordering you observe from the iterators between program runs.From C++14,
std::hash<>
is explicitly permitted to produce different results between different program runs. To quote: