c++ - 为什么我不能使用 std::next_permutation 生成所有排列?
问题描述
我正在尝试使用C++14 STL中的std::next_permutation获取二进制值的所有排列(在这种情况下,由整数 0 和 1 表示) 。
但是,我确实认为我在这种方法中发现了一个错误。
如果向量的末端有一个或多个零,则无法获得向量的所有排列。
例如,让我们考虑向量std::vector<int> a = {1,0,0}
。找到的唯一排列std::next_permutation
是{(1 0 0)}
,而存在三种可能的排列{(1 0 0), (0 1 0), (0 0 1)}
。
这是一个错误吗?如果是这样,我在哪里可以报告?
您可以在此处访问我在 C++ shell 中的代码。它也显示在下面。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a = {1,0,0,0};
std::vector<int> b = {0,0,0,1};
std::cout << "Permutations of a" << std::endl;
do {
for (int i = 0; i < a.size(); i++) {
std::cout << a[i];
}
std::cout << std::endl;
} while (std::next_permutation(a.begin(), a.end()));
std::cout << std::endl << "Permutations of b" << std::endl;
do {
for (int i = 0; i < b.size(); i++) {
std::cout << b[i];
}
std::cout << std::endl;
} while (std::next_permutation(b.begin(), b.end()));
exit(0);
}
输出:
Permutations of a
1000
Permutations of b
0001
0010
0100
1000
解决方案
从参考:
将范围 [first, last) 排列到下一个排列中,其中所有排列的集合按字典顺序相对于 operator< 或 comp 排序。
因此,遍历排列只会为您提供从初始范围开始按字典顺序递增的序列。
请注意,参考页面底部的示例在std::sort
初始范围上执行 a 以生成所有排列。
推荐阅读
- python - statsmodels.discrete.discrete_model.NegativeBinomial.fit() 引发 LinAlgError:“奇异矩阵”
- android-fragments - 片段中的 Kotlin RecyclerView - 导航架构组件 - 空错误
- java - 播放声音作为媒体/闹钟/铃声?
- webpack - 我无法使用 webpack 将编译后的 scss 转换为单个 css 文件
- vb.net - 如何在我的应用程序中使用启动开关?
- javascript - 将函数作为对象成员的闭包
- r - 如何在 R 中计算曼肯德尔统计
- java - 使用生产者-消费者模式的多代理系统?
- java - 使用精灵边框而不是矩形或圆形的精灵之间的 Libgdx 碰撞检测
- javafx - 我如何在 java FX 中创建一个阶段,强制用户首先关闭它以执行其他任何操作?