gpt4 book ai didi

C++出队问题......出队重复返回相同的元素

转载 作者:太空宇宙 更新时间:2023-11-04 14:10:04 24 4
gpt4 key购买 nike

所以我有下面的代码片段...

for(int k=0; k<10; k++){
State newState;
newState = queue.dequeue();
//...do stuff with `newState`...
}

我遇到的问题是,经过几个小时的测试,我意识到每次代码到达 时,newState 都会使 State 的完全相同的实例出队newState = queue.dequeue(),而不是以 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 为空,所以它看起来很可疑。您还可以删除 if/else,因为当 head 为 null 时,count 不会递增。

否则我不明白为什么它会一次又一次地返回相同的元素。唯一的原因可能是一些代码,它多次插入相同的元素。

关于C++出队问题......出队重复返回相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15021387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com