2

I'd prefer to loop through a c++ map in the same way as in this answer:

for (auto& kv : myMap) {
    std::cout << kv.first << " has value " << kv.second << std::endl;
}

Using a range-based for such as this, is it possible to determine that kv is the last element in the range? If so, how?

Community
  • 1
  • 1
  • 2
    If you are not modifying the value. Best to use `auto const&`. – Martin York Apr 15 '14 at 15:17
  • 1
    Could you test if it's equal to myMap.end() - 1? – ooga Apr 15 '14 at 15:17
  • 2
    `&kv == &*m.rbegin();` Why not use a normal for loop instead? Range for is for when you want to iterator entire collection. – jrok Apr 15 '14 at 15:18
  • See related: http://stackoverflow.com/questions/1660195/c-how-to-find-the-biggest-key-in-a-stdmap – EdChum Apr 15 '14 at 15:19
  • Thank you Loki Astari! I do need to loop the entire collection jrok. Thank you all for looking and for great answers! I'm in the weeds right now, so it will take me a short time to confirm. –  Apr 15 '14 at 15:20
  • 1
    @ooga apologies, didn't see the `-1` – EdChum Apr 15 '14 at 15:21

1 Answers1

8

You can get the last key in the map and check for it.

const auto& lastKey = myMap.rbegin()->first;
for (auto& kv : myMap) {
    if(kv.first == lastKey) {
        std::cout << "The last one" << std::endl;
    }
    std::cout << kv.first << " has value " << kv.second << std::endl;
}

You can also use std::prev (reference) if you need the second last or something like that:

const auto& lastKey = std::prev(myMap.end(),2)->first; // gives the 2nd last
Danvil
  • 22,240
  • 19
  • 65
  • 88