Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++?

like image 693
danijar Avatar asked Aug 18 '13 16:08

danijar


People also ask

Is order maintained in unordered_map?

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

Does unordered_map allow duplicates?

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.

Are Keys in unordered map sorted?

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 .


1 Answers

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.

like image 158
Mike Seymour Avatar answered Sep 22 '22 03:09

Mike Seymour