STL: 从reverse到iterator
leetcode:Next Permutation
class Solution { public: void nextPermutation(vector<int> &num) { auto rfirst = num.rbegin(); auto rlast = num.rend(); auto pivot = next(rfirst); while(pivot!=rlast&&*pivot>=*prev(pivot)) { ++pivot; } if(pivot==rlast) { reverse(rfirst,rlast); return; } auto change = find_if(rfirst,pivot,bind1st(less<int>(),*pivot)); swap(*change,*pivot); reverse(rfirst,pivot); } };
首先看一下reverse函数的说明:
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
这个BidirectionalIterator和它的字面意思一样,就是iterators that can be used to access the sequence of elements in a range in both directions (towards the end and towards the beginning).
然后再看一下rfirst和rlast都是什么迭代器:
num.rbegin()返回的是Returns a reverse iterator pointing to the last element in the vector ,num.rend()返回的是 a reverse iterator pointing to the theoretical element preceding the first element in the vector (which is considered its reverse end). 这两个迭代器都是reverse_iterator。这个reverse_iterator事实上都是 random access iterator 类型。
之前经常用的begin()和end(),它们返回的也是random access iterator。
而All random-access iterators are also valid bidirectional iterators.
所以就都可以当成Reverse的参数,来完成vector在指定范围内的反转了。