zoukankan      html  css  js  c++  java
  • 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在指定范围内的反转了。

  • 相关阅读:
    day4-生成器
    第三天-函数
    编码问题
    可变不可变类型总结
    由var与let引起的百度地图所有的覆盖点的信息都是最后一个的
    《企业应用架构模式》 三
    IndexDB
    ESA与SOA
    SOA
    Dubbo(一)
  • 原文地址:https://www.cnblogs.com/parapax/p/3637486.html
Copyright © 2011-2022 走看看