1.next_permutation()函数介绍
1.1 函数介绍
将[first, last)范围内的元素重新排序,并将其排列成为下一个字典序更大的一个排序。通常第三个参数comp可以省略, 也可以自定义排序方式进行排序。
Return : 如果存在下一个字典序排列,将数组进行排列并返回true, 否则返回false。
1.2 函数举例
例如数组 int[ ] = {2, 1, 3}
其按照字典序的全排列为下方所示,如果要输出紧接着的下一个全排列则为{2, 3, 1}。
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
2.prev_permutation()函数介绍
2.1 函数介绍
将[first, last)范围内的元素重新排序,并将其排列成为上一个字典序更小的一个排序。通常第三个参数comp可以省略, 也可以自定义排序方式进行排序。
Return : 如果紧接着的上一个字典序排列存在,将数组进行排列并返回true, 否则返回false。
3.函数代码运行
3.1 函数头文件 “algorithm”
3.2 全排列运行展示
函数是从此排列开始相邻位置的全排列开始变化,所以如果想要输出所有排列必须首先对容器内部的元素进行一个重排列
#include<iostream>
#include<algorithm>
using namespace std;
int a[] = {
2, 1, 3};
int main(){
// 首先输出其所有全排列展示
sort(a, a + 3);
do{
cout << a[0] << ' ' << a[1] << ' ' << a[2] << endl;
}while(next_permutation(a, a + 3));
/* 输出结果
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
}
3.2 函数运行展示
分别输出从此位置开始的上一个全排列和下一个全排列
#include<iostream>
#include<algorithm>
using namespace std;
int a[] = {
2, 1, 3};
int main(){
/*
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
if(next_permutation(a, a + 3)){
// 如果下一个字典序全排列存在则输出
cout << a[0] << ' ' << a[1] << ' ' << a[2] << endl;
}
if(prev_permutation(a, a + 3)){
// 如果上一个字典序全排列存在则输出
cout << a[0] << ' ' << a[1] << ' ' << a[2] << endl;
}
/*
输出:
2 3 1
1 3 2
*/
}