C++全排列函数next_permutation

概述

next_permutation 是 C++ 标准库中的一个函数,位于 < algorithm > 头文件中。它用于生成给定范围内元素的下一个排列,并且会修改原始序列。

函数原型

该函数的原型如下:

template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );

参数 firstlast分别指定了要生成排列的元素范围。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 

  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值