Search code examples
c++hashstlunordered-set

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


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.


Solution

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