繁体   English   中英

将2D数组传递给函数

[英]Passing 2D arrays to function

我试图建立一个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;
    }
}

尝试传递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;
}

在这里很好地描述这个小例子(请参阅Duoas帖子)。

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

由于数组具有编译时已知的维,因此可以使用模板来检测它,如下所示:

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

请注意,此技巧不适用于动态分配的array 在这种情况下,您应该使用类似std::vector

您不需要调整声明中的参数大小,也不需要调整大小,因为[] []语法需要编译时间常数。

用字符串world [] []替换,它应该可以工作。

如果不使用,则使用string [] * world(字符串数组实际上是指向字符串数组的指针的数组)

我希望这会有所帮助,我的C ++越来越生锈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM