0
map<int, string>::reverse_iterator& it = temp.rbegin();

it -> points to garbage key value

it++ -> points to the correct key value

map<int, string>::iterator& it = temp.begin();

it-> points to the correct key value from beginning.

Please assist.

simonc
  • 41,632
  • 12
  • 85
  • 103
  • 1
    Kerrek SB has given the correct answer, but the code you post shouldn't compile: you can't initialize a non-const reference with a temporary. – James Kanze Jul 08 '13 at 08:53

2 Answers2

2

Your statements are incorrect. If temp is not empty, then *temp.rbegin() is indeed the last value in the map, and *temp.begin() is the first value.

(However, the underlying iterator of the reverse begin is the ordinary end iterator - but you don't see that unless you call base() on the reverse iterator.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

You must have an error in your code that's filling the map. You can verify this by testing a trivial example such as

#include <algorithm>
#include <map>
#include <iostream>
using namespace std;

int main()
{
    map<int, char> coll;

    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll[i] = static_cast<char>(i+'a'-1); // because adding 96 is less obvious that we're indexing based at letter a
    }

    // print all element in reverse order
    for_each (coll.rbegin(), coll.rend(),
        []( pair<int, char> mapinfo ) { cout << mapinfo.second << " "; } );
    cout << endl;
}
MichaelH
  • 380
  • 1
  • 7