-5
//Works    
cout << "map[0] value is " << doubleStatsMap.begin()->first<< endl;
//gives error
cout << "map[last value is " << doubleStatsMap.end()->first << endl;

Im simply trying to get the value of the last element of my map. It works correctly with "map.begin->first" but is giving "map/set iterator not dereferencable" for the "map.end()->first". It cant be empty as the map has a beginning thus it has an end. Everything I've read says this should work. Any suggestions greatly appreciated!

Mason
  • 1,662
  • 1
  • 9
  • 10

1 Answers1

2

Trying to get anything from the end iterator causes undefined behavior.

To get the last item, you can use std::map::rbegin().

// cout << "map[last value is " << doubleStatsMap.end()->first << endl;
cout << "map[last value is " << doubleStatsMap.rbegin()->first << endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • THANK YOU. I don't care if I get downvoted for asking this. I saw examples of end and its been driving me crazy. – Mason Aug 23 '17 at 21:47
  • so what is the point of having a "first" and "second" function attached to end(). further, what is the point of even having a [poorly named] end function anyway as maps cannot be referenced like arrays by index anyway? – Mason Aug 23 '17 at 21:54
  • @Mason, good questions. The answers to them are long and not appropriate in a SO comment. – R Sahu Aug 23 '17 at 21:57
  • @Mason `end` is not "poorly named" - read up on half-open ranges. Also, read this: https://stackoverflow.com/questions/13066884/what-is-half-open-range-and-off-the-end-value (especially the accepted answer). – Jesper Juhl Aug 23 '17 at 21:58