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的这些基本用法就足够使用了,进阶的可以搭配其它的数据结构进行使用

加油!!兄弟萌

点个赞呗

版权声明:本文为博主作者:旧林墨烟原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_52115456/article/details/127626074

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2024年4月16日
下一篇 2024年4月16日

相关推荐