next_permutation函数

本文详细介绍了C++中next_permutation()函数的使用方法,包括整型数组、字符数组和字符串的全排列实现,并展示了如何通过自定义比较函数来改变全排列的顺序。

next_permutation()这是一个求全排列的函数,返回值为bool型,如果后面还有排列返回true,否则返回false。

int 类型

int main()
{
 int a[3];
a[0]=1;a[1]=2;a[2]=3;
 do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while (next_permutation(a,a+3));3是要求全排列的长度,和sort一样。

当a数组为3 2 1是返回false

 

char类型

int main()
{
 char ch[205];
cin >> ch;
sort(ch, ch + strlen(ch) );
 char *first = ch;
 char *last = ch + strlen(ch);
 do {
cout<< ch << endl;
}while(next_permutation(first, last));
 return 0;
}
 
把整个ch字符串全都进行排序,按字典升序

 

string 类型

 

int main()
{
 string line;
 while(cin>>line&&line!="#")
{
 if(next_permutation(line.begin(),line.end())) //从当前输入位置开始
cout<<line<<endl;
 else cout<<"Nosuccesor\n";
}
}
 
 
 
int main()
{
 string line;
 while(cin>>line&&line!="#")
{
sort(line.begin(),line.end());//全排列
cout<<line<<endl;
 while(next_permutation(line.begin(),line.end()))
cout<<line<<endl;
}
}

 

 

next_permutation 自定义比较函数
 
 
#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) //'A'<'a'<'B'<'b'<...<'Z'<'z'.
{
 if(tolower(a)!=tolower(b))
 return tolower(a)<tolower(b);
 else
 return a<b;
}
int main()
{
 char ch[20];
 int n;
cin>>n;
 while(n--)
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
 do
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
 return 0;
}

转载于:https://www.cnblogs.com/arno-my-boke/p/4738844.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值