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

Iterate values of a map using range-based for loop

Recently I started using range-based for loop. I had a problem where I needed to sort a map by value and then assign value to vector/array. Can I do that with this loop?

for (auto& it : M){
    // value to vector
}

This question would be the same if I had a vector of pairs, could I just check for second, if it is larger then some other element or number? All this using range-based for loop.

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 :

From C++20, you can use views::values to get at the values of a std::map, or a vector<pair> for that matter:

for (auto v : m | std::views::values)  // m is some map
  // ...

demo

You can similarly get at the keys with views::keys.

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