gpt4 book ai didi

c++ - 循环队列中的 pop() 操作。我如何真正删除该项目?

转载 作者:太空狗 更新时间:2023-10-29 23:17:42 30 4
gpt4 key购买 nike

我正在尝试在 C++ 中使用数组实现一个简单的循环队列。下面是我的代码。

#include <iostream>

int pop();
void push(int );
const int arrayLength = 8;
int inputArray[arrayLength] = {0};
int queueFront=0,queueBack=0;

void push(int theElement)
{
//Check if the push causes queue to overflow
if (((queueBack + 1 ) % arrayLength) == queueFront)
{
std::cout<<"Queue is full."<<std::endl;
return ;
}
inputArray[queueBack] = theElement;
queueBack = (queueBack + 1) % arrayLength;
}


int pop()
{
//Check if queue is already empty

if ( queueFront == queueBack )
{
std::cout<<"Queue is empty."<<std::endl;
}

std::cout<<inputArray[queueFront]<<" removed."<<std::endl;
queueFront = (queueFront + 1 ) % arrayLength;



}

int main()
{
for ( int i =0; i < arrayLength; ++i)
{
std::cout<<inputArray[i]<<std::endl;
}
push(1);
push(2);
push(3);
pop();
push(5);

//printing arrayelements
for ( int i =0; i < arrayLength; ++i)
{
std::cout<<inputArray[i]<<std::endl;
}
}

运行时得到如下输出:

000000001 已删除。1个2个3个5个0000

问题一:1. 我如何实际删除 pop() 操作中的项目?2. 我的实现是否正确?

谢谢

最佳答案

鉴于 pop() 在确定队列为空后仍会更改队列,因此对 #2 的回答是“否”。

关于c++ - 循环队列中的 pop() 操作。我如何真正删除该项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881930/

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