【发布时间】:2021-01-22 20:12:49
【问题描述】:
我正在尝试使用 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 here 中访问我的代码。它也显示在下面。
#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
【问题讨论】:
-
在确定这是一个错误之前,您是否阅读过任何文档?
-
如果
next_permutation在最后一次排列后没有停止,那么您的循环将永远不会结束,因此它确实是一个功能。 -
不要仅仅通过名字来猜测函数的作用,它可能经常出错(不幸的是)
标签: c++ stl c++14 permutation