#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
的调用,但是为什么?
您可以传递比较功能。在此示例中,我传递了一个包含计数器的比较函数:
#include <iostream>
#include <algorithm>
int main()
{
std::array<int, 3> a = {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(std::begin(a), std::end(a))) printArray();
while (std::next_permutation(std::begin(a), std::end(a), [](const auto &, const auto &) {
static std::size_t i = 2 * 6 + 1;
if (i != 0) --i;
return i != 0;
})) printArray();
return 0;
}
每个排列有两个比较。