我目前正在编写C++中的n-puzzle,但由于某些原因,我无法交换板的元素。让我解释。我有一个“Piece”类(这个类的一些方法):C++ - 自定义类型不工作的交换功能
Piece::Piece(int l, int c, int n):
line(l),
column(c),
number(n)
{
}
int Piece::getLine()
{
return line;
}
int Piece::getColumn() const
{
return column;
}
int Piece::getNumber() const
{
return number;
}
void Piece::setLine(const int new_line)
{
this -> line = new_line;
}
void Piece::setColumn(const int new_column)
{
this -> column = new_column;
}
void Piece::setNumber(const int new_number)
{
this -> number = new_number;
}
我也有一个Board类执行游戏。董事会是一个“片”类型的矢量向量。该板正在创建以下代码:
for(size_t i = 0; i < this -> width; i++)
{
vector<Piece> row;
for(size_t j = 0; j < this -> height; j++)
{
row.push_back(Piece(i, j, ((j == this -> width - 1) && (i == this -> height - 1) ? 0 : i * this -> width + j + 1)));
}
board.push_back(row);
}
没有什么是错的,直到这里。问题是我想交换董事会的两个要素。想象一下,我们有一个3x3的游戏。如果我运行下面的代码的结果将是错误的
swapPieces(board[0][0], board[1][0]);
swapPieces(board[1][0], board[2][0]);
cout << board[0][0] << "\t" << board[0][0].getLine() << endl;
拼图是正确的:
但是由执行board [0] [0] .getLine()的输出是1,这是片的初始位置!我真的不知道我做错了什么。我会很感激,如果有人能够给我一个手:)
编辑:swapPieces补充说:
void Board::swapPieces(Piece &p1, Piece &p2)
{
Piece p = p1;
p1 = p2;
p2 = p;
}
至少,我们需要看到更多的代码,显示'board'的确切声明和定义,以及,当然,'swapPieces'。 – 2013-03-18 17:49:10
问题是你没有给我们swapPieces函数的代码,而你知道问题出在这个函数中...... – 2013-03-18 17:51:02
Stephane Rolland:我添加了swapPieces,这是我的错!抱歉。 – pluralism 2013-03-18 17:52:44