C ++在矩阵

时间:2016-12-15 12:56:58

标签: c++ arrays list pointers null

我是c ++的新手,我对指针和NULL之类的东西感到很困惑。

我需要设置一个指向我创建的对象的指针列表的二维数组。我希望在创建对象时将列表设置为NULL。我试图运行它时遇到错误。我不确定是不是因为我对指针或NULL做错了。我将不胜感激任何帮助。

这是我的代码:

GameFullMatrix.h:

private:
    std::list<InGame*>** fullMap;
    int rows,cols;

GameFullMatrix.cpp:

GameFullMatrix::GameFullMatrix(int _rows, int _cols)
{
    this->fullMap = new std::list<InGame*>*[_rows];

    for(int i=0; i<_rows; i++)
    {
        this->fullMap[i] = new std::list<InGame*>[_cols];
        for(int j=0; j<_cols; j++)
        {
            this->fullMap[i][j] = NULL;
        }
    }

this->rows = _rows;
this->cols = _cols;
}

我尝试构建代码时遇到的错误:

  

'operator ='不匹配(操作数类型是'std :: list'和   'long int')|

感谢。

1 个答案:

答案 0 :(得分:1)

fullMap[i][j]的类型为std::list<InGame*>,您无法通过赋值运算符直接将数据插入到列表中。您需要使用fullMap[i][j].push_back(NULL)fullMap[i][j].push_front(NULL)

(std:list中的赋值运算符被重载以将一个列表的内容复制到另一个列表,std::list<InGame*> abc= some variable of type std::list<InGame*>将起作用)

但是为什么你需要在列表中插入NULL,你总是可以通过fullMap[i][j].empty()检查列表是否为空