zoukankan      html  css  js  c++  java
  • C++STL 之排列

    固然我们可以自己使用递归编写全排列程序,但是既然STL里面已将有了这个功能为什么不直接用呢,下面就写一下直接使用C++ STL生成全排序的程序

    函数名:next_permutation

    包含头文件:algorithm

    函数原型:

    template<class BidirectionalIterator>   

    bool next_permutation(BidirectionalIterator _First, BidirectionalIterator _Last    );

    template<class BidirectionalIterator, class BinaryPredicate>   

    bool next_permutation(BidirectionalIterator _First,  BidirectionalIterator _Last, BinaryPredicate _Comp    );

    两个重载函数,第二个带谓词参数_Comp,其中只带两个参数的版本,默认谓词函数为"小于".

    返回值:bool类型(默认若当前调用排列到达最大字典序则返回false,同时重新设置该排列为最小字典序,否则返回true,并按照字典递增的顺序输出下一个排列。例如,在字母表中,abcd的下一单词排列为abdc)

    所以如果是生成一个数组的全排列,先要对数组按升序排序,然后使用do-while语句循环调用next_permutation函数

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<string>
     4 using namespace std;
     5 int main()
     6 {
     7     string str;
     8     cin>>str;
     9     int len=str.length();
    10     char *cstr=(char *)str.c_str();
    11     cout<<"排列输出如下"<<endl;
    12     do
    13     {
    14         cout<<cstr<<endl;
    15     }while(next_permutation(cstr,cstr+len));
    16     cout<<"排列之后cstr变为:"<<endl;
    17     cout<<cstr;
    18     return 0;
    19 }

    上面是一个没有加排序直接调用nextpermation看一下,不同输入的情况下输出结果的比较

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<string>
     4 using namespace std;
     5 int main()
     6 {
     7     string str;
     8     cin>>str;
     9     int len=str.length();
    10     char *cstr=(char *)str.c_str();
    11     sort(cstr,cstr+len);
    12     cout<<"排列输出如下"<<endl;
    13     do
    14     {
    15         cout<<cstr<<endl;
    16     }while(next_permutation(cstr,cstr+len));
    17     cout<<"排列之后cstr变为:"<<endl;
    18     cout<<cstr;
    19     return 0;
    20 }

    加上排序之后,看看效果

  • 相关阅读:
    计算一个整数的二进制中1的个数
    Java 操作 EXCEL
    WIN7 64位配置Oracle SQL Developer工具
    phpstrom+xdebug调试PHP代码
    Zend Server安装后首次运行就出现Internal Server Error的解决
    在C语言中使用scanf语句时遇到的问题总结
    ElementUI中scrollbar的使用解析
    前端模拟手机屏幕图片渐隐渐现效果实现
    谈谈怎么学习编程?
    underScore学习1:匿名函数中call(this)的作用
  • 原文地址:https://www.cnblogs.com/bewolf/p/4412704.html
Copyright © 2011-2022 走看看