簡體   English   中英

初始化由類的構造函數內的向量組成的矩陣

[英]Initializing a matrix made of vectors inside constructor of class

我正在嘗試構建一個具有字符矩陣的游戲。 我正在嘗試使用向量向量來構建我的矩陣。 我的game.h有這個:

#ifndef GAME_H
#define GAME_H
// includes
using namespace std;
class Game 
{
  private:
    int row;
    int col;
    vector<vector<char>>* matrix;
    // other atributtes

  public:
    Game();
    ~Game(){}
    // some functions
};
#endif

在我的game.cpp

Game::Game()
{
    this->col = 20;
    this->row = 20;
    // Initialize the matrix
    this->matrix = new vector<vector<char>>(this->col);
    for(int i = 0 ; i < this->col ; i++)
       this->matrix[i].resize(this->row, vector<char>(row));
    // Set all positions to be white spaces
    for(int i = 0 ; i <  this->col; i++)
      for(int j = 0 ; j < this->row ; j++)
        this->matrix[i][j] = ' ';
}

這給了我一個錯誤:

error: no match for ‘operator=’ (operand types are ‘__gnu_cxx::__alloc_traits<std::allocator<std::vector<char> > >::value_type {aka std::vector<char>}’ and ‘char’)
     this->matrix[i][j] = ' ';
                          ^~~

在線:

this->matrix[i][j] = ' ';

我想知道是什么導致了這個問題,如何在構造函數中將所有內容設置為空格?

this->matrix類型是std::vector<std::vector<char>>*

this->matrix[i]std::vector<std::vector<char>>

this->matrix[i][j]std::vector<char>

因此,

this->matrix[i][j] = ' ';

不起作用。

簡化您的代碼。 matrix更改為

std::vector<std::vector<char>> matrix; // Remove the pointer

相應地調整您的代碼。

如果我是你,我會這樣做:

在games.hpp中:

#ifndef GAME_H
#define GAME_H
// includes
template <class T>
class Game : public std::vector<std::vector<T>>
{
     private:
        int row;
        int col;

    public:
        Game();
       ~Game(){}
// some functions
};
#endif

在games.cpp中

template<class T>
Game<T>::Game(int rr=20, int cc=20):
    row(rr), col(cc), std::vector<std::vector<T>>(rr, std::vector<T>(cc))
{
 //empty body   
}

這自然會使您訪問元素的方式變得復雜,但可以通過重載operator()來輕松完成,該operator返回對您要訪問的位置的引用。 注意通過公開繼承std :: vector,我們繼承了它們的所有運算符和成員函數和變量。 因此,我們還繼承了std :: vector類中的重載operator []。 因此,我們可以通過重載運算符訪問任何元素,如下所示:

template<class T>
T& Game<T>::operator()(int rr, int cc){
return this->operator[](rr)[cc];
}

在上面的return語句中,第一部分使用參數rr調用重載的operator [],該參數返回一個矢量對象,在這個矢量對象上,我們通過使用參數'cc'作為列索引調用它來再次調用重載的operator [] (正如我們對std :: vector對象[index]所做的那樣)

有了這個代碼肯定看起來優雅和專業:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM