我在从 vector 的 vector 创建板时遇到了一些问题
我需要类似的东西
a b c d e f g h i j
A . . . . . . . . . .
B . . . . . . . . . .
C . . . . . . . . . .
D . . . . . . . . . .
E . . . . . . . . . .
F . . . . . . . . . .
G . . . . . . . . . .
H . . . . . . . . . .
I . . . . . . . . . .
J . . . . . . . . . .
大小可以改变(取决于我已经在构造函数中“提取”的一些 txt 信息)。 我试过这样的事情:
void Board::display() const{
//string filename;
Board b1("configp1.txt");
int upC = 65, lowC = 97; //ascii code for low a and upper A
int icc = 0; //int char coluna
cout << b1.numLines << endl;
cout << b1.numColumns << endl;
cout << "lol" << endl;
for(int i = 0; i < b1.numLines; i++){
for (int j = 0; j < b1.numColumns; j++){
board[i][j] == '.';
}
}
while (icc < b1.numLines){ //o int char coluna vai aumentando consoante as dimensoes do tabuleiro || e.g Se tivermos um tab 10x10
cout << (char)lowC << " "; //teremos um range de 65-75 [a-j] para as colunas e um range 97 -107 [A-J] para as linhas
icc++;
lowC++;
}
cout << endl;
icc = 0;
for (int y = 0; y<b1.numLines; y++)
{
cout << (char)upC << " ";
for (int x = 0; x < b1.numColumns; x++){
cout << board[y][x] << " ";
}
cout << endl;
upC++;
}
板构造器:
Board::Board(const string &filename){
string nome;
unsigned int size;
char simb;
unsigned int cor;
char ori;
PositionChar position;
string tmp;
ifstream config;
config.open(filename.c_str()); //abre o ficheiro config onde estao as informacoes do tabuleiro
if (config.is_open()) {
config >> tmp >> numLines >> tmp >> numColumns;
while (!config.eof()) {
config >> simb >> tmp >> position.lin >> position.col >> tmp >> ori >> tmp >> size >> tmp >> cor;
if(!config.fail()){
ships.push_back(Ship(simb, position, ori, size, cor));
}
}
}
else{
cout << "Ficheiro de config invalido" << endl;
exit(1);
}
config.close();
板类:
class Board {
public:
Board(const string &filename);
int putShip(const Ship &s);
void moveShips();
//bool checkLimits()
//bool attack(const Bomb &b);
void display()const;
void show()const;
int getLines();
int getColumns();
private:
int numLines, numColumns;
vector<Ship> ships;
vector <vector <int> > board;
};
但是什么也没有发生。
有人可以帮帮我吗??
最好的问候
最佳答案
您的电路板被定义为 vector 的 vector :vector <vector <int> > board;
但是在构造函数中,你没有初始化它。你也不在显示功能中。所以它是空的。正在尝试访问 board[i][j]
在这种情况下会出界。
解决方案:
我建议在构造函数中,一旦已知维度,就可以通过以下方式调整 vector 的大小:
board.resize(numLines, vector<int> (numColumns,'.'));
其他问题:
请注意以下代码不应出现在display() const
中因为你打算修改 board
:
for(int i = 0; i < b1.numLines; i++){
for (int j = 0; j < b1.numColumns; j++){
board[i][j] == '.'; /// <=======OOOPS ! Won't change anything this is comparison
}
}
这只能编译因为你写了==
, 所以比较 board[i][k]
与 '.'
无需更改。这可以解释为什么什么都没有发生(显示 0 不会产生任何可见的东西)。
请注意,Board::display()
中还有另一个潜在问题.您在那里创建一个局部变量 Board b1
为了使用 b1.numLines
和 b1.numColumns
.这很容易出错:你应该摆脱这个无用的 b1
直接引用numLines
和 numColumns
,它们都是成员变量,其优点是确保获得您在其自己的构造函数中为对象设置的值。
关于c++ - 从 vector 的 vector 创建一个板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30144224/