1

我正在研究地图生成器。我正在使用二维向量来保存数据。

标题:

class MapGenerator
{
public:
     ...
protected:
    std::vector< std::vector<int> > map;
...
}

一旦 MapGenerator 被实例化,它的大小就知道了,我想知道是否有一种更清洁的方法来正确调整它的大小并用 0 填充它,而不是我目前所做的:

MapGenerator::MapGenerator(int dimensionX, int dimensionY) 
: dimensionX(dimensionX), dimensionY(dimensionY)
{
    map.resize(dimensionX);

    for(int i = 0 ; i < map.size() ; i++)
    {
       map[i].resize(dimensionY);
       fill(map[i].begin(), map[i].end(), 0);
    }

}

此代码工作正常,但如果有更清洁或更优化的方法,我想知道。我在 MinGW 下使用 GCC,但我认为我没有启用 C++ 11。

4

3 回答 3

2

I'd start with a 2D array class, something like this:

template <class T>
class array_2D { 
    std::vector<T> data;
    size_t cols;
public:
    array_2D(size_t x, size_t y) : cols(x), data(x*y) {}

    T &operator()(size_t x, size_t y) { return data[y*cols+x]; }
};

There's no need to explicitly zero-fill it. When you create or resize a std::vector, you pass a value that will be used to fill the new "empty" spaces. If you don't pass another value explicitly, it'll use T(), which will work out to 0 in the case of built-in arithmetic types (short, int, long, etc.)

Note that as written, this uses parentheses for addressing (like Fortran or BASIC), so to create a 2D array and fill it with random numbers, you could do something like this:

array_2D<int> x(10, 10);

for (int i=0; i<10; i++)
    for (int j=0; j<10; j++)
        x(i, j) = rand();

It's possible to write a class that does 2D addressing using x[i][j] syntax, but it's enough more complex that unless you're really set on that syntax, it's easier to avoid it. If You really want that, you can see an example (with a 3D array class) in an older answer.

于 2012-12-02T19:24:48.020 回答
1

通过为地图本身使用额外的类而不使事情复杂化,这似乎是最简单的方法。

如果您希望避免“填充”函数调用,您可能想查看该行是否

fill( map[i].begin(), map[i].end(), 0)

可以用你自己的循环替换,例如“

for(int j = 0 ; j < map[i].size() ; j++){ map[i][j] = 0;}

它可能不会增加您的时间复杂度,但可能会影响您的空间复杂度。

于 2012-12-02T20:54:28.183 回答
0

resize有第二个参数,它是要填充的值。一个明确map[i].resize(dimensionY, 0)的就足够了。

于 2012-12-02T19:22:56.743 回答