Home > OS >  Retrieve first key of std::multimap, c
Retrieve first key of std::multimap, c

Time:11-20

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.

CodePudding user response:

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 you can get rid of the loop and for a non-empty map it is just:

 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.

  • Related