【C++ STL应用与实现】62: 如何使用std::next_permutation

20 篇文章 1 订阅
2 篇文章 0 订阅

本系列文章的目录在这里:目录. 通过目录里可以对STL总体有个大概了解

前言

本文介绍STL中的排列算法:next_permutation

示例

// ****************************************************************************
RUN_GTEST(PermutationTest, Basic, @);

vector<int> v;
v.resize(3);
iota(v.begin(), v.end(), 1);

int count(0);
do {
    printContainer(v, format("the %d-th perm: ", ++count));
} while (next_permutation(v.begin(), v.end()));

pln(format("total perm: %d", count));

END_TEST;


static std::string format(const char *fmt, ...) {
    va_list args, args1;
    va_start(args, fmt);
    va_copy(args1, args);

    string res(1 + vsnprintf(nullptr, 0, fmt, args1), 0);
    va_end(args1);

    vsnprintf(&res[0], res.size(), fmt, args);
    va_end(args);

    return res;
}

运行结果:

the 1-th perm: 1 2 3
the 2-th perm: 1 3 2
the 3-th perm: 2 1 3
the 4-th perm: 2 3 1
the 5-th perm: 3 1 2
the 6-th perm: 3 2 1
total perm: 6

源码及参考链接


作者水平有限,对相关知识的理解和总结难免有错误,还望给予指正,非常感谢!

在这里也能看到这篇文章:github博客, CSDN博客, 欢迎访问

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值