c++ 中所有 class 个实例中的可变向量大小

Variable vector size in all class instantiations in c++

我正在尝试编写一个用于终端的国际象棋游戏。一场比赛由棋盘class、棋子class组成。对于每一块,如果棋盘上没有其他块,我想确定允许的移动,并将其放入 vector> (a1 = 1,1).

您可以想象,皇后比棋子有更多的允许移动。理想情况下,我希望我的 Piece 有一个可变大小的向量,这样它就充满了特定 Piece 的移动。

这是我的 Piece 实例化:

class Piece{
 private:
  int row;
  int col;
  // number of moves made by the piece
  int moveCnt;
  // white = 1, black = -1
  int color;
  // 'p', 'n', 'b', 'r', 'q', 'k' 
  char type;
  // permissable moves for the piece
  vector<pair<int,int>> permMoves;
  // allowable moves for the piece, taking the entire board into account (1. Ke2 is not allowed but permissable)
  vector<pair<int,int>> allowedMoves;

然后对于允许的允许移动我这样做:

void Piece::computePermMoveS(){
vector<pair<int,int>> emptyPermMoves {{0,0}};
  permMoves.swap(emptyPermMoves);
  // PAWN
  if (getType() == 'p'){
    // add move to one row ahead
    pair<int,int> add_pair (getCol(),getRow()+1*getColor());
    permMoves.push_back(add_pair);
    if (getMoveCnt() == 0){
      // add move to two rows ahead
      pair<int,int> add_pair (getCol(),getRow()+2*getColor());
      permMoves.push_back(add_pair);
    }
    cout << "new pawn at " << getCol() << ", " << getRow() << endl;
    for (int i=0; i<sizeof(permMoves)/sizeof(permMoves[0]); i++){
      cout << permMoves[i].first << ", " << permMoves[i].second << endl;
    }
  }

最后的打印语句用于调试目的。如果我编译并 运行 这个,我得到每个棋子 (pawn, rook) 都有三个允许的移动(作为一个 pawn,循环中的第一个棋子有 -> 0 0, a3, a4)。

谁能告诉我如何解决这个问题?我尝试用

保留 21 步(最可能的)
Piece(){
    permMoves.reserve(21);
    allowedMoves.reserve(21);
  }

但这不是我想要的解决方案,我也没有得到它的工作。所以我真的很想使用每个棋子的原始方法,每个棋子都有其独特的允许移动。

for (int i=0; i<sizeof(permMoves)/sizeof(permMoves[0]); i++)

此行不正确。 std::vector 中的条目数由 size() 成员函数给出:

for (size_t i=0; i<permMoves.size(); i++){
  cout << permMoves[i].first << ", " << permMoves[i].second << endl;
}

您所做的是假设 std::vector 与数组一样工作,但事实并非如此。

执行循环更简单的方法是使用 ranged-based for loop 代替:

for (auto& p : permMoves)
    cout << p.first << ", " << p.second << endl;