[英]How to generate distinct permutations of a vector in C++?
Suppose that there is a vector with only binary elements like this:假设有一个只有二进制元素的向量,如下所示:
X = [0, 0, 1, 1]
The only distinct permutations are:唯一不同的排列是:
X = [0, 0, 1, 1]
X = [0, 1, 0, 1]
X = [0, 1, 1, 0]
X = [1, 0, 0, 1]
X = [1, 0, 1, 0]
X = [1, 1, 0, 0]
Is there an efficient way to do this in C++?有没有一种有效的方法可以在 C++ 中做到这一点?
Use std::next_permutation
:使用std::next_permutation
:
#include <algorithm>
#include <array>
#include <cstdio>
int
main()
{
std::array<int, 4> arr{ 0, 0, 1, 1 };
/* Sort the array if necessary */
std::sort(arr.begin(), arr.end());
do {
for (auto const e : arr)
std::printf("%d ", e);
std::putchar('\n');
} while (std::next_permutation(arr.begin(), arr.end()));
}
Output:输出:
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.