Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading