【易错点】关于全排列函数 next_permutation

文章介绍了C++中`next_permutation`函数在C风格数组和STLvector容器中的使用方法,强调了在调用前需要对数组进行升序排序的重要性,以及函数会从当前排列继续而非从头开始生成全排列的特性。

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

对于C风格数组 ( int arr[n] ),用法:

next_permutation( arr, arr+n )

对于C++ STL vector容器( vector<int> vec ),用法:

next_permutation( vec.begin(), vec.end() )


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int n;
//next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列
//next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。
void myPrint(int n)
{
	cout << n << " ";
	return;
}
int main()
{

	scanf_s("%d", &n);
	vector<int>v;
	for (int i = 1; i <= n; i++)
		v.push_back(i);
	do
	{
		for_each(v.begin(), v.end(), myPrint);
		cout << endl;
	} while (next_permutation(v.begin(), v.end()));
	return 0;
}

注意一:当使用 next_permutation 函数后,数组已经变成下一个排列;

注意二:next_permutation 函数不会自动从 第一个排列 开始,而是从 当前序 开始,因此若要得到所有全排列,应事先将数组排好序(升序)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值