所以我有下面的代码片段......
for(int k=0; k<10; k++){
State newState;
newState = queue.dequeue();
//...do stuff with `newState`...
}
我遇到的问题是,经过数小时的测试,我意识到每次代码到达时都会newState
将完全相同的实例出列,而不是以 FIFO 方式弹出一个新元素......我似乎无法弄清楚找出我到底做错了什么:/State
newState = queue.dequeue()
下面是我的队列类 .h 和 .cpp 代码...
//queue.h
#include <iostream>
#include <stdio.h>
#include "state.h"
using namespace std;
// Node class
class Node {
public:
State elem;
Node* next;
Node() {}
State Elem() { return elem; }
Node* Next() { return next; }
};
// Queue class
class Queue {
Node *head;
Node *tail;
public:
Queue();
~Queue();
bool isEmpty();
int size();
void enqueue(State);
State dequeue();
};
和我的 .cpp 文件...
//queue.cpp
#include "queue.h"
#include <iostream>
Queue::Queue(){
head = NULL;
tail = NULL;
}
Queue::~Queue(){
if(!isEmpty()){
while(head){
Node *del = head;
head = head->next;
delete del;
}
}
}
bool Queue::isEmpty(){
return head == NULL;
}
int Queue::size(){
int count = 0;
if(isEmpty()){
return count;
} else {
Node *temp = head;
while(temp){
temp = temp->next;
count++;
}
delete temp;
return count;
}
}
//insert s to back of queue
void Queue::enqueue(State s){
Node* newNode = new Node();
newNode->elem = s;
newNode->next = NULL;
if(s.checkZ()){
cout << "Puzzle solved!" << endl << endl;
exit(0);
}
if(head==NULL){
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
//remove State from front of queue
State Queue::dequeue(){
if(isEmpty()){
cout << "This puzzle has no solution." << endl;
cout << "Exiting program..." << endl << endl;
exit(0);
} else {
State ret = head->Elem();
Node *del = head;
head = head->next;
delete del;
return ret;
}
}
提前感谢您的帮助,我很乐意根据请求显示我的代码的任何其他片段
编辑:这是我的状态复制构造函数......
State::State(const State &rhs){
pieces = rhs.pieces;
pieceCount = rhs.pieceCount;
rows = rhs.rows; cols = rhs.cols;
currentState = rhs.currentState;
prevStates = rhs.prevStates;
prevStateCount = rhs.prevStateCount;
moves = rhs.moves;
moveCount = rhs.moveCount;
}