这里是使用评论区中
T.C.提到的链接(
http://howardhinnant.github.io/combinations.html)的代码:
#include "../combinations/combinations"
#include <iostream>
#include <vector>
int
main()
{
std::vector<int> v{0, 1, 2, 3};
typedef std::vector<int>::iterator Iter;
for_each_permutation(v.begin(), v.begin()+3, v.end(),
[](Iter f, Iter l)
{
for (; f != l; ++f)
std::cout << *f << ' ';
std::cout << "| ";
return false;
}
);
std::cout << '\n';
}
0 1 2 | 0 2 1 | 1 0 2 | 1 2 0 | 2 0 1 | 2 1 0 | 0 1 3 | 0 3 1 | 1 0 3 | 1 3 0 | 3 0 1 | 3 1 0 | 0 2 3 | 0 3 2 | 2 0 3 | 2 3 0 | 3 0 2 | 3 2 0 | 1 2 3 | 1 3 2 | 2 1 3 | 2 3 1 | 3 1 2 | 3 2 1 |
这个库相较于 std::next_permutation 的一个显著优势是,被置换的元素不需要被排序,甚至不需要可比较。例如:
#include "../combinations/combinations"
#include <iostream>
#include <vector>
enum class color
{
red,
green,
blue,
cyan
};
std::ostream&
operator<< (std::ostream& os, color c)
{
switch (c)
{
case color::red:
os << "red";
break;
case color::green:
os << "green";
break;
case color::blue:
os << "blue";
break;
case color::cyan:
os << "cyan";
break;
}
return os;
}
int
main()
{
std::vector<color> v{color::blue, color::red, color::cyan, color::green};
typedef std::vector<color>::iterator Iter;
for_each_permutation(v.begin(), v.begin()+3, v.end(),
[](Iter f, Iter l)
{
for (; f != l; ++f)
std::cout << *f << ' ';
std::cout << "| ";
return false;
}
);
std::cout << '\n';
}
蓝 红 青绿 | 蓝 青绿 红 | 红 蓝 青绿 | 红 青绿 蓝 | 青绿 蓝 红 | 青绿 红 蓝 | 蓝 红 绿 | 蓝 绿 红 | 红 蓝 绿 | 红 绿 蓝 | 绿 蓝 红 | 绿 红 蓝 | 蓝 青绿 绿 | 蓝 绿 青绿 | 青绿 蓝 绿 | 青绿 绿 蓝 | 绿 蓝 青绿 | 绿 青绿 蓝 | 红 青绿 绿 | 红 绿 青绿 | 青绿 红 绿 | 青绿 绿 红 | 绿 红 青绿 | 绿 青绿 红 |
s
数字集合,然后使用std::next_permutation
函数? - T.C.s
中的 scramble 是什么意思? - 101010