Get a reverse iterator from a forward iterator without knowing the value type

前端 未结 2 520
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 01:41

I\'m trying to implement some STL-style sorting algorithms. The prototype for std::sort looks something like this (from cplusplus.com):

template         


        
相关标签:
2条回答
  • 2020-12-02 02:14

    The STL has std::reverse_iterator<Iterator>:

    template <class RandomAccessIterator>
    void mySort(RandomAccessIterator first, RandomAccessIterator last) 
    {
      typedef std::reverse_iterator<RandomAccessIterator> RIter;
      RIter riter(last);
      RIter rend(first);
      for ( ; riter != rend; ++riter) {
        // Do stuff
      }
    }
    

    An important note:

    Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is changed to point to the last element (not past it) of the range (this would be the first element of the range if reversed). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the range if reversed).

    0 讨论(0)
  • 2020-12-02 02:21

    Check out the base() method of reverse_iterator.

    0 讨论(0)
提交回复
热议问题