c++入门必学库函数 next_permutation

一、next_permutation的介绍

next_permutation的意思是下一个排列,与其相对的是prev_permutation,即上一个排列。我们需要使用全排列的时候就可以直接使用这两个函数,方便又快捷

二、next_permutation的基本用法

由于prev_permutation和next_permutation的用法是一样的,下面就值讲解next_permutation的基本用法

next_permutation只能获得下一个排列,如果要获得全排列,那么就需要先对数组进行升序排序

基本定义如下:
next_permutaion(起始地址,末尾地址+1)
next_permutaion(起始地址,末尾地址+1,自定义排序)

可以使用默认的升序排序,也可以使用自定义的排序方法

1、普通数组全排列

普通数组可以通过数组名表示地址,非常容易实现

示例代码:

#include<iostream>
#include<algorithm>//使用 next_permutation()和sort()需要导入的头文件 
using namespace std;
int main(){
	int a[4]={2,1,4,3};
	
	sort(a,a+4);//对数组排序 
	
	do{
		for(int i=0;i<4;i++){//打印排列 
			cout<<a[i]<<' ';
		}
		cout<<endl;
	}while(next_permutation(a,a+4));//获取下一个排列 
} 

运行结果:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

2、结构体全排列

结构体默认是不能比较大小的,那么就不能使用默认的next_permutation()排列比较函数,需要使用自定义排列比较函数

示例代码:

#include<iostream>
#include<algorithm>//使用 next_permutation()和sort()需要导入的头文件 
using namespace std;

struct test{//结构体test 
	int val;
}; 

bool cmp(test t1,test t2){//自定义的排列 
	return t1.val<t2.val;
}

int main(){
	test t[4];//结构体数组 
	t[0].val=1;
	t[1].val=2;
	t[2].val=3;
	t[3].val=4;
	
	do{
		for(int i=0;i<4;i++){//打印排列 
			cout<<t[i].val<<' ';
		}
		cout<<endl;
	}while(next_permutation(t,t+4,cmp));//获取下一个排列 
} 

运行结果:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

3、vector

vector及string等数据结构不能直接用名字代表地址,只能够使用自带的迭代器begin()、end()实现全排列

示例代码:

#include<iostream>
#include<vector> //使用vector需要导入的头文件 
#include<algorithm>//使用 next_permutation()和sort()需要导入的头文件 
using namespace std;

int main(){
	vector<int> v;//定义一个int型的vector 
	v.push_back(1);//在尾部插入数据1 
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	
	do{
		for(int i=0;i<v.size();i++){//打印排列 
			cout<<v[i]<<' ';
		}
		cout<<endl;
	}while(next_permutation(v.begin(),v.end()));//获取下一个排列 
} 

运行结果:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

同样地,prev_permutation拥有同样的用法,大家可以动手尝试一下

学完next_permutation的这些基本用法就足够使用了,进阶的可以搭配其它的数据结构进行使用

加油!!兄弟萌

点个赞呗

  • 93
    点赞
  • 305
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧林墨烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值