c++ - 为什么 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
这里从来没有发生过这种情况,但为什么呢?
解决方案
您可以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;
}
}
推荐阅读
- javascript - req.query 导致空对象
- ios - 为什么 AVAsset 状态变化的观察者不起作用?
- microservices - 我们可以在最终一致性期间使用 hystrix 回滚吗?
- javascript - 谁能告诉我为什么这个电子邮件验证不起作用?
- python - 如何保存表示在 Tensorflow 中构建的神经网络的对象
- c# - 无法使用集合绑定数据网格将新记录添加到数据库
- sql-server - 如何将 SSIS 包构建到从 Salesforce 到 SQL Server 数据库的 UPSERT/DELETE 数据?
- mysql - MongoDB 4.0:电子商务应用
- c# - 我收到“AccountEmail 字段是必需的”。使用 FromHeader 属性将值传递给 API 时
- php - 如何获得正确的json?