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++?
No, it is not possible. Usage of std::unordered_map doesn't give you any guarantee on element order. If you want to keep elements sorted by map keys (as seems from your example) you should use std::map . If you need to keep list of ordered pairs you can use std::vector<std::pair<std::string,int>> .
Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.
The keys are automatically sorted in a strict-weak ordering. If you need another sort, write your own comparator. If you only need to print it sorted, the following may be inefficient, but it's as close as you'll get if you still want to keep the unordered_map .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With