繁体   English   中英

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

[英]Variable vector size in all class instantiations in c++

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

您可以想象,对于皇后,您比棋子拥有更多允许的移动。 理想情况下,我希望我的棋子有一个可变大小的向量,所以它只填充了该特定棋子的动作。

这是我的 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;
    }
  }

最后一个打印语句用于调试目的。 如果我编译并运行它,我会发现每一块(棋子,车)都有三个允许的移动(作为棋子,循环中的第一个有 -> 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()成员 function 给出:

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

您正在做的是假设std::vector与数组的工作方式相同,但事实并非如此。

执行循环的一种更简单的方法是使用基于范围的for循环

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM