The order in which unordered_map changes when assigned

I am interested in this behavior. I found that the destination unordered_mapchanges the internal order of the unordered map without entering / deleting:

unordered_map<int, string> m1;
unordered_map<int, string> m2;
unordered_map<int, string> m3;

m1[2] = "john";
m1[4] = "sarah";
m1[1] = "mark";

m2 = m1;
m3 = m2;

for(auto it = m1.begin(); it != m1.end(); ++it) {
    cout << it->second << " ";
}
cout << endl;
for(auto it = m2.begin(); it != m2.end(); ++it) {
    cout << it->second << " ";
}
cout << endl;
for(auto it = m3.begin(); it != m3.end(); ++it) {
    cout << it->second << " ";
}
cout << endl;

outputs:

mark sarah john 
john sarah mark 
mark sarah john

I know that unordered_mapno particular order is supported due to the fact that it is a hash table internally, so inserting an element can end anywhere, and re-hash will mix it all.

However, here the order changes immediately after the appointment. I expected that the order would be the same as I thought, it would just copy the underlying storage.

, , , , , unordered_map . (m3) m2, m2 m3.

?

- Apple LLVM 8.1.0 (clang-802.0.42)

+4
2

lib++:

    _LIBCPP_INLINE_VISIBILITY
    unordered_map& operator=(const unordered_map& __u)
    {
#ifndef _LIBCPP_CXX03_LANG
        __table_ = __u.__table_;
#else
        if (this != &__u) {
            __table_.clear();
            __table_.hash_function() = __u.__table_.hash_function();
            __table_.key_eq() = __u.__table_.key_eq();
            __table_.max_load_factor() = __u.__table_.max_load_factor();
            __table_.__copy_assign_alloc(__u.__table_);
            insert(__u.begin(), __u.end());
        }
#endif
        return *this;
    }

lib++ unordered_map header

, ++ 11 , , -, __u.

, :

m2 = m1;

:

m2.clear();
m2.max_load_factor(m1.max_load_factor());
m2.insert(m1.begin(), m1.end());

, libstd++, operator= - = default (. libstd++ unordered_map header)

+2

, , ( ), .

mark john , , . ( ), , , .

+2

Source: https://habr.com/ru/post/1683463/


All Articles