STLalgorithm算法next_permutation,prev_permutation(39)


STLalgorithm算法next_permutation,prev_permutation(39)

next_permutation原型:

std::next_permutation

default (1)
template <class BidirectionalIterator>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last);
custom (2)
template <class BidirectionalIterator, class Compare>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last, Compare comp);

该函数是返回范围序列内元素的下一个更大的(根据字典序进行比较)排列。并将该排列存放到该范围内。

如果成功则返回true,如果当前范围的序列已经是最大的了,则返回false.

一个简单的例子:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void nextpermutation(){
    vector<int> vi{1,3,2};
    cout<<"at first vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;
    cout<<"next_permutation(vi.begin(),vi.end())"<<endl;
    while(next_permutation(vi.begin(),vi.end())){
        for(int i:vi)
            cout<<i<<" ";
        cout<<endl;
    }
    cout<<"all greater permutation show on!"<<endl;


}

运行截图:




pre_permutation原型:

std::prev_permutation

default (1)
template <class BidirectionalIterator>
  bool prev_permutation (BidirectionalIterator first,
                         BidirectionalIterator last );
custom (2)
template <class BidirectionalIterator, class Compare>
  bool prev_permutation (BidirectionalIterator first,
                         BidirectionalIterator last, Compare comp);

该函数和next_permutation刚好相反,是返回一个更小的排列。

返回值也是true或者false,规则也是一样。

一个简单的例子:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void prevpermutation(){
    vector<int> vi{2,3,1};
    cout<<"at first vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;
    cout<<"pre_permutation(vi.begin(),vi.end())"<<endl;
    while(prev_permutation(vi.begin(),vi.end())){
        for(int i:vi)
            cout<<i<<" ";
        cout<<endl;
    }
    cout<<"all smaller permutation show on!"<<endl;


}

运行截图:

——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:coderguang@gmail.com

2014-9-19

于GDUT

——————————————————————————————————————————————————————————————————


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注