Is for(auto i : unordered_map) guaranteed to have the same order every time?

c++, for-loop, standards, unordered-map

Solution

The iteration order of unordered associative containers can only change when rehashing as a result of a mutating operation (as described in C++11 23.2.5/8). You are not modifying the container between iterations, so the order will not change.

Although the specification doesn't explicitly state that rehashing can't occur at any other time, doing so would invalidate all iterators over the container, making any iteration at all impossible.

Problem

When I iterate over a `std::unordered_map` with the range based for loop twice, is the order guaranteed to be equal? ``` std::unordered_map<std::string, std::string> map; std::string query = "INSERT INTO table ("; bool first = true; for(auto i : map) { if(first) first = false; else query += ", "; query += i.first; } query += ") "; query += "VALUES ("; first = true; for(auto i : map) { if(first) first = false; else query += ", "; query += i.second; } query += ");" ``` In the example above, the resulting string should be in that form. Therefore, it is important that both times, the order of iteration is the same. ``` INSERT INTO table (key1, key2, key3) VALUES (value1, value2, value3); ``` Is this guaranteed in C++?

Original source

Related problems