首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++STL 之排列

C++STL 之排列

作者头像
用户1215536
发布2018-02-05 14:31:31
6490
发布2018-02-05 14:31:31
举报

固然我们可以自己使用递归编写全排列程序,但是既然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 }

加上排序之后,看看效果

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-04-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档