jeudi 28 mai 2015

The sentence in bold below, in the book "The Standard Library" by Nocolai Josuttis, is not clear to me

I'm reading "The Standard Library", second edition, by Nicolai Josuttis. In its page 183 we have:

Examples of Using Unordered Maps and Multimaps

The example presented for multimaps on page 179 also works for an unordered multimap if you replace map by unordered_map in the include directive and multimap by unordered_multimap in the declaration of the container:

#include <unordered_map>
...
unordered_multimap<int,string> coll;
...

The only difference is that the order of the elements is undefined. However, on most platforms, the elements will still be sorted because as a default hash function, the modulo operator is used.

I emphasized in bold the part that is not clear to me. My first impression when I read this was that the author is saying that both programs (the one in page 179, see below) and the one above) should print the name of the cities in the same order on most platforms. But this doesn't happen in clang and GCC. See live examples for map and unordered_map in GCC. The same results are obtained in clang.

After thinking for a while I interpreted the author as saying that the names of the cities are printed in the same order for almost all platforms, when processed with a unordered_map, and the output seems to confirm this. But even so, it's difficult for me to accept this interpretation, as different implementations will probably use different hash functions!

Below, you'll find the example in page 179 referred to above:

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
    multimap<int,string> coll; // container for int/string values
    // insert some elements in arbitrary order
    // - a value with key 1 gets inserted twice
    coll = { {5,"tagged"},
             {2,"a"},
             {1,"this"},
             {4,"of"},
             {6,"strings"},
             {1,"is"},
             {3,"multimap"} };
    // print all element values
    // - element member second is the value
    for (auto elem : coll) {
        cout << elem.second << ’ ’;
    }
    cout << endl;
}

Aucun commentaire:

Enregistrer un commentaire