队列实现C++
Queue realisation C++
我对队列的实现以一种奇怪的方式工作:当我将新元素排队时 - 一切都正确,但是当我开始取消排队时 - 它删除了最后一个添加的元素,尽管此时我的头是 1 并且尾巴更大。C++索引的特点是什么?为什么它的行为是这样的?这是我的完整代码:https://hastebin.com/odibusacuk.cpp
class Queue{
public:
int head=1;
int tail=1;
int q[MAX];
int Queue::enqueue(int x){
if (isFull()){
return 0;}
else {
q[tail]=x;
cout << tail << " here is a tailn";
if (tail==sizeof(q)){
cout << tail << " this is tailn" ;
tail=1;}
else {
tail=tail+1;
}
return x;
}
}
int Queue::dequeue(){
if(isEmpty()){
cout << " the queue is emptyn";
return 0;}
else {
int x=q[head];
if (head==sizeof(q)){
head=1;}
else {
head=head++;
return x;}
}
return 0;
}
你遇到的问题是因为当你做类似的事情时
cout << k.enqueue(4) << " " << k.enqueue(9) << ' ' << k.enqueue(6) << " " << k.enqueue(3) << " enqueuedn ";
没有指定这些函数的调用顺序。在您的示例中,从右到左调用它们。这意味着您的队列实际上是
{ 0, 3, 6, 9, 4 }
0 在那里,因为您跳过元素 0 并直接转到元素 1。您的头指向 1,因此您将取消排队 3。
您可以在此处阅读更多内容。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的