next_permutation && prev_permutation in C++

本文介绍了如何在C++中使用`next_permutation`生成数组和字符串的全排列,并展示了如何利用`prev_permutation`实现逆序排列,通过实例展示了如何操作整数数组和字符串,以实现从大到小的排列方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个是C++里面用于生成全排列的函数
很好用,不仅能对数组进行全排列,还能对字符串进行全排列,但是必须保证字符串内的数组是有序的。当然,我们也可以用sort对字符串内的字符进行排序

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

int main()
{
	string s;
	s="213";
	sort(s.begin(),s.end());
	do{
		cout << s << endl;
	}while(next_permutation(s.begin(),s.end()));
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述
对于数组也是同样的使用方法

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

int main()
{
	int a[]={1,2,3};
	do{
		cout << a[0] << a[1] << a[2] << endl;
	}while(next_permutation(a,a+3));
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述
当然现在都是小的数字在前,大的数字在后,有没有什么办法反一反呢?

当然是有的,C++里面还带了一个prev_permutation函数
上代码

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
	int a[]={3,2,1};
	do{
		cout << a[0] << a[1] << a[2] << endl;
	}while(prev_permutation(a,a+3));
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值