gpt4 book ai didi

c++ - 如何创建二维字符串数组的排列?

转载 作者:行者123 更新时间:2023-11-27 22:54:06 27 4
gpt4 key购买 nike

我有以下代码。我将每个框设置为 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

无需单独设置它们?

最佳答案

就个人而言,我会将数组存储为一维 std::vector<int>尺寸n*n .然后你可以打电话 std::next_permutation() 就可以了,很简单。 (值得注意的是,您不必使用 std::vector ;只要它在内存中是连续的,您就应该能够正确使用 std::next_permutation())

要使排列逻辑成为“2D”,您唯一需要做的就是将其打印出来。但是,您的循环按原样应该可以正确处理,因此也没有问题。

编辑:重新阅读您的代码后,您无法按原样使用它。相反,您应该初始化 1D std::vector处处为 0,位置 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;
}

关于c++ - 如何创建二维字符串数组的排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34776720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com