我试图创建一个ASCII世界,但是我无法在函数之间传递2D数组。它是一个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;
}
}发布于 2013-05-01 22:35:24
尝试传递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 post)。
所以我希望这篇文章能描述做类似事情的不同方式。然而,这看起来确实很丑陋,而且可能不是最好的编程实践(我会尽一切努力避免这样做,动态数组非常好,您只需要记住发布它们)。
发布于 2013-05-01 22:40:35
由于您的数组具有编译时已知的维度,因此可以使用模板来检测它,如下所示:
template <std::size_t W, std::size_t H>
void place_house(string (&world)[W][H])
{
int max_house = (W * H) / 10; //One tenth of the map is filled with houses
int xcoords = (0 + (rand() % 20));
int ycoords = (0 + (rand() % 20));
world[xcoords][ycoords] = "@";
}
// ...
place_house(world); // Just pass it请注意,对于动态分配的数组,此技巧不起作用。在这种情况下,您应该使用类似于std::vector的内容。
发布于 2013-05-01 22:36:30
您不需要调整声明中参数的大小,也不能这样做,因为语法需要编译时间常量。
替换为string world,它应该可以工作。
如果不是,则使用string[]* world (字符串数组的数组实际上是指向字符串数组的指针数组)
我希望这能帮上忙,我的C++已经越来越生疏了。
https://stackoverflow.com/questions/16320069
复制相似问题