九、STL算法-变序算法(random_shuffle、reverse、next_permutation)

来源:互联网 发布:淘宝出售订单如何下载 编辑:程序博客网 时间:2024/05/22 14:00

STL算法-变序算法(random_shuffle、reverse、next_permutation)

一、简介

变序算法具有以下几个特征:

  1. 改变容器中元素的顺序
  2. 但是不改变元素的值
  3. 不适用于关联容器
  4. 算法复杂度都是O(n)的

二、变序算法

成员函数

成员函数

random_shuffle,随机打乱[first,last) 中的元素, 适用于能随机访问的容器

template <class RanIt>void random_shuffle(RanIt first, RanIt last);

reverse,颠倒区间[first,last)顺序

template <class BidIt>void reverse(BidIt first, BidIt last);

next_permutation,求下一个排列

template <class InIt>bool next_permutaion (Init first,Init last);

三、程序示例

#include <algorithm>#include <iostream>#include <vector>#include <iterator>#include <list>using namespace std;int main(){    //下一个排列     string str = "123";    while(next_permutation(str.begin(), str.end())){        cout<<str<<endl;    }    cout<<"**********"<<endl;     //上一个排列     int a[] = {10, 8, 7};    list<int> l(a, a+3);    while(prev_permutation(l.begin(), l.end())){        list<int>::iterator i;        for(i=l.begin(); i!=l.end(); i++)            cout<<*i<<" ";        cout<<endl;    }    cout<<"**********"<<endl;     ostream_iterator<int> oit(cout, " ");    //倒序     int b[] = {7, 8, 9, 10, 11, 12};    reverse(b, b+6);    copy(b, b+6, oit);    cout<<endl<<"**********"<<endl;     //随机排列     int c[] = {0, 1, 2, 3, 4};    random_shuffle(c, c+5);    copy(c, c+5, oit);    return 0;}

输出:

132
213
231
312
321
**********
10 7 8
8 10 7
8 7 10
7 10 8
7 8 10
**********
12 11 10 9 8 7
**********
4 1 3 2 0

0 0