版权声明:本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名elloop(包含链接) https://blog.csdn.net/elloop/article/details/53958797
本系列文章的目录在这里:目录. 通过目录里可以对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
源码及参考链接
作者水平有限,对相关知识的理解和总结难免有错误,还望给予指正,非常感谢!