试图用数组的数字使所有数字可能
Trying to make every number possibility with digits from array
我有以下数组:
int a[3]={1, 2, 3};
注意:我不知道该数组有多少个元素。
我想输出
123;132;213;231;312;321。
但是,我不知道阵列中有多少位数字。同样的数字也无法重复。
正如评论所说,听起来您想要std :: next_permunt,这是使用它的方法:
int main()
{
std::vector<int> a{ 1, 2, 3 };
std::sort(a.begin(), a.end());
do {
std::cout << a << "; ";
} while (std::next_permutation(a.begin(), a.end()));
return 0;
}
请注意,您需要operator<<()
的超载:
std::ostream& operator<<(std::ostream& s, const std::vector<int>& v)
{
for (auto&& item : v)
s << item;
return s;
}
该程序的输出是
123;132;213;231;312;321;
您甚至可以做一些实用程序:
void permutations(std::ostream& s, std::vector<int> a)
{
std::sort(a.begin(), a.end());
do {
s << a << "; ";
} while (std::next_permutation(a.begin(), a.end()));
}
permutations(std::cout, a);
std::cout << "n";
permutations(std::cout, { 3, 1, 4, 2 });
,因此它永远存在。你有n!置换。
最容易递归地写出该函数,列举第一个数字,然后从N-1中获得第二位,第三位来自N-2等。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象