tags:

views:

218

answers:

2

I want to find an element in the map using map::find(key), and then iterate the map in reverse order from the point where I found the element, till the beginning (i.e. until map::rend()).

However, I get a compile error when I try to assign my iterator to a reverse_iterator. How do I solve this?

+4  A: 

Converting an iterator to a reverse iterator via the constructor should work fine, e.g. std::map<K, V>::reverse_iterator rit(mypos).

A minimal example using std::vector:

#include <vector>
#include <iostream>
#include <algorithm>

int main() {
  typedef std::vector<int> intVec;
  intVec vec;
  for(int i = 0; i < 20; ++i) vec.push_back(i);

  for(intVec::reverse_iterator it(std::find(vec.begin(), vec.end(), 10));
      it != vec.rend(); it++)
    std::cout << *it;
}
pmr
thanx guys for the quick response. This did it (altho i dint have time to tryout the others.)
OverTheEdge
+1. Note that the key part of this answer is replacing `it = ..` with `it (..)`, so that the explicit ctor can be used.
Roger Pate
Thanks Rodger, it is indeed one of the constructors of reverse_iterator and _not_ the copy constructor. My bad.
pmr
+1  A: 

Make the conversion explicit:

std::map<int, int> SomeMap;

for ( int i = 0; i < 10; i++)
    SomeMap[ i ] = i;

std::map<int, int>::iterator it = SomeMap.find( 5 );
std::map<int, int>::reverse_iterator itr( it );

for ( itr; itr != SomeMap.rend( ); itr++ )
    std::cout << itr->first << std::endl;
Space_C0wb0y