std::tr1::unordered_map is ordered instead

626 Views Asked by At

I'd like to have an unordered_map which contains the occurrences of each key; the problem is that, when I print myMap, it's ordered instead. I know it'd be better to use C++11, but I cannot for some reasons I'm not going to explain.

#include <iostream>
#include <tr1/unordered_map>

using namespace std;
using std::tr1::unordered_map;

main () {
    unordered_map<int,int> myMap;
    int counter, key;

    cin>>counter;
    for (int i=0; i<counter; i++) {
        cin>>key; // Read key from keyboard
        if (myMap.find(key) == myMap.end()) // If key is not already present in myMap
            myMap[key] = 1; // Insert the new key with 1 occurrence
        else
            myMap[key]++; // Increment the current key occurrence
    }
    for (unordered_map<int,int>::const_iterator it = myMap.begin(); it != myMap.end(); ++it)
        cout << "[" << it->first << "," << it->second << "] " << endl;
}
0

There are 0 best solutions below