Reverse iteration from this map iterator

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

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

+3
source share
2 answers

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

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;
}
+9
source

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;
+2
source

Source: https://habr.com/ru/post/1733866/


All Articles