c++ - c ++中所有类实例化中的可变向量大小
问题描述
我正在尝试编写一个国际象棋游戏以在终端中使用。一个游戏由一个 Board 类组成,由 Piece 类组成。对于每个棋子,如果棋盘上没有其他棋子,我想确定允许的移动,并将其放入 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++)
此行不正确。a 中的条目数std::vector
由size()
成员函数给出:
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;
推荐阅读
- google-sheets - 谷歌表格 - 如何获得第一个和最后一个值?
- c# - EF Core - Add unique index
- php - 单击指向另一个页面的href链接时PHP单例丢失实例
- twilio - Twilio Video JS:静音 RemoteParticipant 的音频
- typo3 - TYPO3 6.2:如何限制相关页面中显示的链接数量(基于关键字)
- sql - 使用 sql stmt 从日期表中查找最近的未来或等于日期
- android-ndk - HelloCardboard 示例:sdk 在 Gradle 中不可见
- php - PHP Cron 作业备份到 Google Drive
- javascript - 从 React 应用程序内部访问 Bootstrap 方法
- bazel - Bazel的http_file调试认证