Retrieve first key of std::multimap, c++

I want to retrieve just the first key of a multimap. I already achieved it with iterating through the multimap, taking the first key and then do break. But there should be a better way, but I do not find it.

int store_key;
std::multimap<int, int> example_map; // then something in it..
for (auto key : example_map)
{
    store_key = key;
    break;
}

This solves the Problem, but I am searching for another solution.

>Solution :

Your range based for loop is more or less (not exactly but good enough for this answer) equivalent to:

for (auto it = example_map.begin(); it != example_map.end(); ++it) {
    auto key = *it;

    store_key = key;
    break;
}

I hope now it is clear that for a non-empty map you can get rid of the loop and just write:

 auto store_key = *example_map.begin();

Note that store_key is a misnomer, because it is not just the key and your code would trigger a compiler error. It is a std::pair<const int,int>. store_key->first is the key.

Leave a Reply