Is there any order exists in unordered_set in c++?

109 Views Asked by At
int main(){
    unordered_set<int> S;
    S.insert(1);
    S.insert(10);
    S.insert(100);
    S.insert(64);

    for(auto &x: S){
        cout<<x<<" ";
    }
    cout<<endl;
    S.erase(S.find(1),S.end());
    for(auto &x: S){
        cout<<x<<" ";
    }
    
}

Output:

64 1 100 10 
64

This is same for every IDE and for every time. Isn't unordered_set uses hash? And hash don't have an order.

3

There are 3 best solutions below

0
On BEST ANSWER

Indeed it's a poor name. I believe the C++ standards committee wanted to call it std::hash_set but there were too many so-called std::hash_sets in circulation prior to standardisation in C++11. The same applies to std::unordered_map: see the hash_map of the Boost distribution targeting C++03 and earlier.

They are indeed ordered insofar that hashing buckets are ordered, but the main point one needs to make is that you're not supposed to care about the order.

(Fortunately in C++17 boost::optional grew into std::optional: hopefully lessons were learnt, and something like std::discretionary avoided.)

0
On

This is same for every IDE and for every time.

Not promising anything about the order of elements is not the same as promising a different order every time.

And hash don't have an order.

There are elements, and they can be iterated. That's an order. They aren't in a natural order.

0
On

Hash is deterministic, so unordered_set is deterministic, else you would not be able to retrieve the elements in the set.

The order you see is simply the content of the buckets in the unordered_set, the order can change if the unordered_set decide to resize.