首页 > 解决方案 > 为什么 STL 的置换函数在这里不起作用?

问题描述

#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这里从来没有发生过这种情况,但为什么呢?

标签: c++stlpermutation

解决方案


您可以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;
    }
}

Live On Coliru


推荐阅读