如何创建 2D 字符串数组的排列
How do I create a permutation of a 2D string array?
我有以下代码。我将每个框设置为等于 1。现在我想一次将 3 个框设置为 0。如何在不手动将它们中的每一个设置为 1 的情况下执行此操作?
是否有一个排列公式将当时的 3 设置为 1?
#include <iostream>
using namespace std;
int main()
{
int array[2][2];
for (int x = 0; x<2; x++)
{
for (int y = 0; y<2; y++)
array[x][y] = 1;
}
// display all cells to see that all of them are set to zero
cout << "diplaying" << endl;
for (int x = 0; x<2; x++)
{
for (int y = 0; y<2; y++)
cout << array[x][y] << " " ;
cout << endl;
}
打印它看起来像这样。
1 1
1 1
现在我该如何打印
0 1
0 0
和
1 0
0 0
和
0 0
1 0
和
0 0
0 1
而不必以这种方式单独设置它们?
就个人而言,我会将数组存储为大小为 n*n
的一维std::vector<int>
。然后你可以非常简单地打电话给std::next_permutation()
。(值得注意的是,你不必使用std::vector
;只要它在内存中是连续的,你应该能够正确使用std::next_permutation()
)
使排列逻辑"2D"的唯一一件事就是将其打印出来。但是,您的循环按原样应该正确处理,因此也没有问题。
编辑:重新读取代码后,您无法按原样使用它。相反,您应该将 1D std::vector
初始化为除位置 0 的 1 之外的所有位置。然后,它的排列将产生您想要的输出。
此外,您的打印循环将无法正确打印出数组。您可能希望:
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
std::cout << vector[i*2+j] << " " ;
}
std::cout << std::endl;
}
仔细阅读后,我是这样解释你的问题的:你想从这里开始
1 1
1 1
对此
0 1
0 0
使用 for
子句。
如果您只想保持单元格不变..您可以保存它并在用0
填充数组后恢复它。
memo = array[0][1];
for (int x = 0; x<2; x++) {
for (int y = 0; y<2; y++) {
array[x][y] = 0;
}
}
array[0][1] = memo;
如果这是你想做的。
顺便说一下,"字符串数组"在哪里..?
我会写一个函数来打印所有零,除了需要打印实际值的地方,然后使用不同的索引调用这个函数以获得所需的效果。
#include <iostream>
using namespace std;
#define SZ 2
void printValue(int a [SZ][SZ], int x, int y)
{
for(int i=0; i<SZ; ++i )
{
for(int j=0; j<SZ; ++j)
{
if(i==x && j==y) cout<<a[i][j];
else cout<<"0";
cout<<" ";
}
cout<<endl;
}
}
现在您可以在 for 循环中使用此函数
int main()
{
int arr[SZ][SZ];
for (int x = 0; x<SZ; x++)
{
for (int y = 0; y<SZ; y++)
arr[x][y] = 1;
}
// display all cells to see that all of them are set to zero
cout << "diplaying" << endl;
for (int x = 0; x<SZ; x++)
{
for (int y = 0; y<SZ; y++)
cout << arr[x][y] << " " ;
cout << endl;
}
//now display all combos:
for(int i=0; i<SZ; ++i)
{
for(int j=0; j<SZ; ++j)
{
printValue(arr, i,j);
}
cout<<"nn";
}
}
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组