std::next_permutation 是 C++ 标准库中的一个算法,用于重新排列给定范围内的元素,以产生按字典序排列的下一个排列(如果存在)。如果不存在下一个排列(即已经是最大排列),那么该函数会将范围排序为最小的排列(即升序排列)。
函数原型
template< class BidIt >
bool next_permutation( BidIt first, BidIt last );
template< class BidIt, class Compare >
bool next_permutation( BidIt first, BidIt last, Compare comp );
first, last:定义要重新排列的范围的迭代器。
comp:一个可选的比较函数或函数对象,用于确定元素之间的顺序。
返回值
如果成功生成下一个排列,则返回 true;否则返回 false(即已经是最大排列)。
用法示例
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
do {
for (int i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
在这个示例中,有一个包含三个元素的向量 {1, 2, 3}。使用 do-while 循环和 std::next_permutation 来打印出该向量的所有可能的排列。输出将是:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
此外,如果想要生成按字典序排列的前一个排列,可以使用 std::prev_permutation。用法同上