这里是使用T.C. 在 cmets (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';
}
蓝色红色青色|蓝色青色红色|红色蓝色青色|红青蓝|青色
蓝红|青红蓝|蓝红绿|蓝绿红|红蓝
绿色 |红绿蓝|绿蓝红|绿红蓝|青色
绿色 |蓝绿青色|青蓝绿|青绿色蓝色|绿色
蓝色青色 |绿色青色蓝色|红青绿|红色绿色青色|青色
红绿|青绿色红色|绿色红色青色|青青红|