简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM