1、next_permutation()
函数
1.1 基本介绍
1.1.1 定义
用于重新排列给定范围内的元素到下一个字典序排列。如果当前排列已经是最后一个排列,则该函数会将其调整为第一个排列(即升序排列),并返回 false;否则,它将排列调整为下一个更大的排列,并返回 true
1.1.2 限制
定义于头文件
<algorithm>
中
1.1.3 场景
主要用于生成给定序列的所有可能排列,特别适用于需要遍历所有排列组合的问题
1.2 基础用法
1.2.1 生成整数数组的所有排列
#include <iostream>
#include <algorithm> // 包含next_permutation函数
int main() {
int arr[] = {1, 2, 3};
std::sort(std::begin(arr), std::end(arr)); // 先对数组进行排序
do {
for (int num : arr) {
std::cout << num << ' ';
}
std::cout << '\n';
} while (std::next_permutation(std::begin(arr), std::end(arr)));
return 0;
}
1.2.2 自定义比较函数
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct LengthCompare {
bool operator()(const std::string &a, const std::string &b) const {
return a.length() < b.length();
}
};
int main() {
std::vector<std::string> words = {"apple", "fig", "banana", "date"};
std::sort(words.begin(), words.end(), LengthCompare()); // 根据长度排序
do {
for (const auto& word : words) {
std::cout << word << ' ';
}
std::cout << '\n';
} while (std::next_permutation(words.begin(), words.end(), LengthCompare()));
return 0;
}
注意:
- 在使用
std::next_permutation
之前,一般需要先对数据进行升序排序,以确保从最小的排列开始- 当没有更多的排列时,
std::next_permutation
返回false
并将范围恢复为初始状态(即最小排列)
2、prev_permutation()
函数
2.1 基本介绍
2.1.1 定义
用于将给定范围内的元素重新排列为前一个字典序排列。如果当前排列已经是第一个排列(即升序排列),则该函数会将其调整为最后一个排列,并返回
false
;否则,它将排列调整为前一个更小的排列,并返回true
2.1.2 限制
定义于头文件
<algorithm>
中
2.1.3 场景
主要用于生成给定序列的所有可能排列中的前一个排列,特别适用于需要从后往前遍历所有排列组合的问题
2.2 基础用法
2.2.1 生成整数数组的所有排列,从最大的排列开始直到最小的排列
#include <iostream>
#include <algorithm> // 包含prev_permutation函数
int main() {
int arr[] = {1, 2, 3};
std::sort(std::begin(arr), std::end(arr), std::greater<int>()); // 先对数组进行降序排序
do {
for (int num : arr) {
std::cout << num << ' ';
}
std::cout << '\n';
} while (std::prev_permutation(std::begin(arr), std::end(arr)));
return 0;
}
2.2.2 自定义比较函数
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct LengthCompare {
bool operator()(const std::string &a, const std::string &b) const {
return a.length() > b.length(); // 注意这里是降序
}
};
int main() {
std::vector<std::string> words = {"apple", "fig", "banana", "date"};
std::sort(words.begin(), words.end(), LengthCompare()); // 根据长度降序排序
do {
for (const auto& word : words) {
std::cout << word << ' ';
}
std::cout << '\n';
} while (std::prev_permutation(words.begin(), words.end(), LengthCompare()));
return 0;
}
注意:
- 在使用
std::prev_permutation
之前,通常需要先对数据进行降序排序,以确保从最大的排列开始- 当没有更多的排列时,
std::prev_permutation
返回false
并将范围恢复为初始状态(即最大排列)
微语录:每一个不曾起舞的日子,都是对生命的辜负。让生活充满热情与活力,你会发现平凡中蕴含的无限可能。