gpt4 book ai didi

c++ - 将二维数组传递给函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:03 25 4
gpt4 key购买 nike

我正在尝试创建一个 ASCII 世界,但是我无法在函数之间传递二维数组。这是一个 20 x 20 的数组,我想在其中随机放置房屋。数组不会像我希望的那样通过,我的教程告诉我全局变量是邪恶的,所以没有这些的解决方案会很棒。

using namespace std;

void place_house(const int width, const int height, string world[width][length])
{
int max_house = (width * height) / 10; //One tenth of the map is filled with houses
int xcoords = (0 + (rand() % 20));
int ycoords = (0 + (rand() % 20));
world[xcoords][ycoords] = "@";
}

int main(int argc, const char * argv[])
{
srand((unsigned)time(NULL));
const int width = 20;
const int height = 20;
string world[width][height];
string grass = ".";
string house = "@";
string mountain = "^";
string person = "Å";
string treasure = "$";
//Fill entire world with grass
for (int iii = 0; iii < 20; ++iii) {
for (int jjj = 0; jjj < 20; ++jjj) {
world[iii][jjj] = ".";
}
}
place_house(width, height, world);
for (int iii = 0; iii < 20; ++iii) {
for (int jjj = 0; jjj < 20; ++jjj) {
cout << world[iii][jjj] << " ";
}
cout << endl;
}
}

最佳答案

尝试传递 string ** 而不是 string[][]

所以你的函数应该这样声明:

void place_house(const int width, const int height, string **world)

然后您以常规方式访问您的数组。

请记住正确处理边界(可能您想将它们与数组一起传递)。


编辑:

这就是您实现所需目标的方式:

#include <string>
#include <iostream>
using namespace std;

void foo (string **bar)
{
cout << bar[0][0];
}

int main(void)
{
string **a = new string*[5];
for ( int i = 0 ; i < 5 ; i ++ )
a[i] = new string[5];

a[0][0] = "test";

foo(a);

for ( int i = 0 ; i < 5 ; i ++ )
delete [] a[i];
delete [] a;
return 0;
}

编辑

实现您想要实现的目标的另一种方法(将静态数组传递给函数)是将其作为一个维数组传递,然后使用类似 C 的方式访问它。

例子:

#include <string>
#include <iostream>
using namespace std;

void foo (string *bar)
{
for (int r = 0; r < 5; r++)
{
for (int c = 0; c < 5; c++)
{
cout << bar[ (r * 5) + c ] << " ";
}
cout << "\n";
}
}

int main(void)
{
string a[5][5];
a[1][1] = "test";
foo((string*)(a));
return 0;
}

这个小例子描述得很好 here (参见 Duoas 帖子)。

所以我希望这将描述做类似事情的不同方法。然而,这看起来确实很丑陋,并且可能不是最佳编程实践(我会尽一切努力避免这样做,动态数组非常好,您只需要记住释放它们)。

关于c++ - 将二维数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320069/

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