所以我有下面的代码片段。。。
for(int k=0; k<10; k++){
State newState;
newState = queue.dequeue();
//...do stuff with `newState`...
}
我遇到的问题是,经过几个小时的测试,我意识到每次代码到达newState = queue.dequeue()
时,newState
都会将完全相同的State
实例出列,而不是以FIFO的方式弹出一个新元素。。。我似乎不明白我到底做错了什么:/
下面是我的队列类.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::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;
}
在size()
中
delete temp;
虽然没有危险,但由于temp此时为null,所以看起来很可疑。您也可以删除if/else
,因为当head为null时,count
不会递增。
否则,我不明白为什么它会一次又一次地返回相同的元素。唯一的原因可能是一些代码,它多次插入相同的元素。