0

I have a sorted std::vector and I have to using the reverse_iterator for searching. It does return me the reverse_iterator for the element I search for. But I need to know the corresponding the forward iterator in the vector. I search the stackoverflow and it shows several posts that people recommend to use base() for conversion

vector<double>::reverse_iterator rit = std::upper_bound(sortData.rbegin(), sortData.rend(), 0.3);

cout << "the element in the vector with reverse iterator is " << *rit << endl;

However, in the post I found, people said to tell the corresponding forward iterator, I need to use (rit+1).base() instead of rit.base(), I don't understand why. If I do that way, I can't retrieve the same element. So I use rit.base() instead, so is it right?

vector< double >::iterator it=rit.base();
cout << "the element in the vector with forward iterator is " << *it << endl;
user1285419
  • 2,183
  • 7
  • 48
  • 70
  • 2
    No, add one before `.base`, or subtract one after and remember to check for `end` before. It is a quirk of how reverse iterator is implemented and the valid addresses near an array (one before begin is not valid) – Yakk - Adam Nevraumont Jul 28 '13 at 19:51
  • but if I access the element by (rit+1).base(), it doesn't return the element I expected. – user1285419 Jul 28 '13 at 20:25
  • @user18285419 give a simple, complete, compiling example that demonstrates your problem (not a code snippet that is incomplete, or an overly complex code dump). http://sscce.org Also note that `upper_bound` returns the one-past-the-end element in the passed range: `upper_bound( rbegin, rend ).base()` is equivalent to `lower_bound( begin, end )`, but `*upper_bound( rbegin, rend)` != `*lower_bound( begin, end )`. – Yakk - Adam Nevraumont Jul 28 '13 at 20:38
  • I am so sorry. I don't know why, but I run my testing code again. I figure out I should use (rit+1).based() to get the right answer. I apologize the first few time when I compile the code, it doesn't give me the right answer but it is fine now :( – user1285419 Jul 28 '13 at 21:28
  • Closed as a dupe. Refer [this answer](http://stackoverflow.com/a/2037917/514235), for why to use *"(rit+1).base() instead of rit.base()"*. – iammilind Mar 16 '17 at 11:00

0 Answers0