全排列函数:nest_permutation函数,和prev_permutation函数浅解

全排列函数:nest_permutation函数,和prev_permutation函数

1.next_permutation函数定义:next_permutation(start, end, cmp)

2.prev_permutation函数定义:prev_permutation(start, end, cmp)

3.全排列函数的头文件保存在#include <algorithm>头文件中。

4.next_permutation函数用于全排列时,元素必须都以从小到大的升序形式进行排列。

而prev_permutation函数用于全排列时,元素必须都以从大到小的降序形式进行排列。

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[3] = {1, 2, 3};
do
{
cout << arr[0] << ' ' << arr[1] << ' ' << arr[2] <<'\n';
}while (next_permutation(arr, arr + 3));
system("pause");
return 0;
}

其结果为:

但当把while (next_permutation(arr, arr + 3))改为while (next_permutation(arr, arr + 时)),结果就变成了

由此可以引出:

1.next_permutation(num, num + n), n表示为对n个元素进行排序

2.当使用next_permutation 函数时 int arr[3]中的元素必须都是以从小到大的升序形式排列,但是亦可以通过cmp传参来改变int arr[3]中的元素是否是以升序或降序的形式排列

例如:

#include <iostream>
#include <algorithm>
using namespace std;
bool compare(int a, int b)//通过给cmp传参改变arr[3]中元素的排列方式
{
return a > b;
}

int main()
{
int arr[3] = {3, 2, 1};
do
{
cout << arr[0] << ' ' << arr[1] << ' ' << arr[2] <<'\n';
}while (next_permutation(arr, arr + 3, compare));
system("pause");
return 0;
}

注意:全排列函数一般于sort函数一起使用,使元素按从小到大或从从大到小的顺序排列。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

呼啦啦的风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值