如何从C ++中的函数返回矩阵(板)?

问题描述 投票:0回答:3

我正在制作一个简单的游戏,需要我创建一个由用户定义的大小的棋盘。

我一直在编写一个函数,该函数应该返回我将用于游戏的电路板(矩阵),但是我似乎无法使其正常工作。

[我尝试使用嵌套的for循环方法在主函数中打印出矩阵,但是我很难实现它并从函数返回它。

int* boardStateDead(int width, int height){

    int* board_dead_state[width][height];

    for(int i = 0; i < height; i++){

        for(int j = 0; j < width; j++){
            board_dead_state[i][j] = 0;

        }
    }
    return  board_dead_state;
}

我希望函数能够返回指向刚创建的矩阵的指针。

c++ arrays matrix
3个回答
0
投票

我建议您创建一个简单的类或结构来保持您的董事会状态。在内部,使用std::vector,因此您不必担心管理内存。

如果需要,甚至可以重载operator[](int)以使其像2D数组一样起作用。

#include <vector>

class Board
{
public:
    Board(int width, int height)
        : mWidth(width)
        , mHeight(height)
        , mState(width * height)
    {}

    int* operator[](int row) { return mState.data() + row * mWidth; }
    const int* operator[](int row) const { return mState.data() + row * mWidth; }

    int Width() const { return mWidth; }
    int Height() const { return mHeight; }

private:
    int mWidth, mHeight;
    std::vector<int> mState;
};

现在,当您知道它的大小时,只需构造它:

Board board(width, height);

std::vector的构造函数会将所有值初始化为零。

您可以通过使用我添加的方法访问它来打印出来:

for (int row = 0; row < board.Height(); row++)
{
    for (int col = 0; col < board.Width(); col++)
    {
        std::cout << ' ' << board[row][col];
    }
    std::cout << std::endl;
}

或者更好的是,在板上做另一种方法,例如Print()


0
投票

您正在堆栈中创建板阵列,超出范围后将被删除。另外,您还将其创建为整数指针数组而不是整数数组。

我建议您使用新语句创建它:

int* board_dead_state = new[width*height];

然后设置初始值,请使用:

memset(board_dead_state, 0, width*height*sizeof(int));

或将您的for循环修改为:

for(int i = 0; i < height; i++){
    for(int j = 0; j < width; j++){
        int offset = i * width + j
        board_dead_state[offset]= 0;
    }
}

从函数返回指针后,您有责任使用delete []语句来分配它。

您可以制作一个董事会课程来在需要时处理分配和取消分配。


0
投票

这是在您的代码中使用的方法:

int** boardStateDead(int width, int height){

    int** board_dead_state = new int*[height];

    for(int i = 0; i < height; i++){
        board_dead_state[i] = new int[width];
        for(int j = 0; j < width; j++){
            board_dead_state[i][j] = 0;
        }
    }
    return  board_dead_state;
}

然后您会得到这样的内容:

int** state = boardStateDead(someWidth, someHeight);

并访问其元素,例如state[i][j]。最后,但也许,最重要的是,当您完成使用它后,像这样释放它的内存:

          for (int i = 0; i < height; i++)
          {
            delete[] state[i];
          }
          delete[] state;
© www.soinside.com 2019 - 2024. All rights reserved.