马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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并将范围恢复为初始状态(即最大排列)
微语录:每一个不曾起舞的日子,都是对生命的辜负。让生存充满热情与活力,你会发现平常中蕴含的无限大概。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |