概述
next_permutation 是 C++ 标准库中的一个函数,位于 < algorithm > 头文件中。它用于生成给定范围内元素的下一个排列,并且会修改原始序列。
函数原型
该函数的原型如下:
template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
参数 first 和 last分别指定了要生成排列的元素范围。first 是一个迭代器,指向排列的起始位置,而 last 是一个迭代器,指向排列的结束位置(不包含在排列中)。
std::next_permutation 函数会将当前序列变成下一个字典序更大的排列,并返回 true 表示成功生成了下一个排列;如果已经是最后一个排列,那么函数会将序列变为第一个排列,并返回 false。
范例1
下面是一个示例代码,演示了 std::next_permutation 函数的使用:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3};
// 首先对数组进行排序
std::sort(nums.begin(), nums.end());
// 输出初始排列
do {
std::cout << "当前排列: ";
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
} while (std::next_permutation(nums.begin(), nums.end()));
return 0;
}
输出结果如下:
当前排列: 1 2 3
当前排列: 1 3 2
当前排列: 2 1 3
当前排列: 2 3 1
当前排列: 3 1 2
当前排列: 3 2 1
范例2
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3};
// 首先对数组进行排序
std::sort(nums.begin(), nums.end());
// 输出初始排列
std::cout << "初始排列: ";
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
// 生成下一个排列并输出
while (std::next_permutation(nums.begin(), nums.end())) {
std::cout << "下一个排列: ";
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
输出结果如下:
初始排列: 1 2 3
下一个排列: 1 3 2
下一个排列: 2 1 3
下一个排列: 2 3 1
下一个排列: 3 1 2
下一个排列: 3 2 1