#include <iostream>
#include <algorithm>
int main()
{
int a[3] = {2, 1, 3};
auto printArray = [&a]() -> void
{
for (const auto& e : a) std::cout << " " << e;
std::cout << "\n";
};
// My doubts are here
while (std::prev_permutation(a, a + 3)) printArray();
while (std::next_permutation(a, a + 3)) printArray();
return 0;
}
输出:
1 3 2
1 2 3
但是我认为输出将是:
1 3 2
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
似乎没有在这里发生对next_permutation
的调用,但是为什么?
您可以在最后一次调用std::reverse
之后将std::reverse
数组:
std::prev_permutation
[int main()
{
std::array<int, 3> a {2, 1, 3};
using std::begin; using std::end;
while (std::prev_permutation(begin(a), end(a))) {
std::cout << a << std::endl;
}
std::reverse(begin(a), end(a));
assert(std::is_sorted(begin(a), end(a)));
while (std::next_permutation(begin(a), end(a))) {
std::cout << a << std::endl;
}
}
] >>
您可以传递比较功能。在此示例中,我传递了一个包含计数器的比较函数: