c++ - Is for(auto i : unordered_map) guaranteed to have the same order every time? -
when iterate on std::unordered_map
range based loop twice, order guaranteed equal?
std::unordered_map<std::string, std::string> map; std::string query = "insert table ("; bool first = true; for(auto : map) { if(first) first = false; else query += ", "; query += i.first; } query += ") "; query += "values ("; first = true; for(auto : map) { if(first) first = false; else query += ", "; query += i.second; } query += ");"
in example above, resulting string should in form. therefore, important both times, order of iteration same.
insert table (key1, key2, key3) values (value1, value2, value3);
is guaranteed in c++?
the iteration order of unordered associative containers can change when rehashing result of mutating operation (as described in c++11 23.2.5/8). not modifying container between iterations, order not change.
although specification doesn't explicitly state rehashing can't occur @ other time, doing invalidate iterators on container, making iteration @ impossible.