dimanche 3 janvier 2016

Can I rely on the order of an unordered map?

I have an std::unordered_multimap and I want to get the last inserted element of a specific key. I observed this behaviour:

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main() {
    unordered_multimap<string, string> mmap;

    mmap.emplace("a", "first");
    mmap.emplace("a", "second");
    mmap.emplace("a", "last");
    mmap.emplace("b", "1");
    mmap.emplace("b", "2");
    mmap.emplace("b", "3");

    auto last_a = mmap.equal_range("a").first;
    auto last_b = mmap.equal_range("b").first;

    cout << last_a->second << endl;
    cout << last_b->second << endl;

    return 0;
}

This code outputs:

last
3

This is, at least, on GCC, the behaviour I want. Can I rely on this? Does the standard say simething about the order the std::unordered_multimap store things? If not, what would be the best alternative?

Aucun commentaire:

Enregistrer un commentaire