c++ - 尝试将队列打印为数组

标签 c++ data-structures queue

我正在尝试将队列的内容打印为数组。我有代码工作和编译。问题是当我多次调用该函数时,打印函数不会调用并且不会再次打印该数组。我需要多次打印数组,但它没有打印出来。

打印函数的代码是:

template <class Type>
 void queueType<Type>::debugArray() 
 {
   for(queueFront; queueFront<count; queueFront++){
    cout << "[" << queueFront<< "] ," << list[queueFront] << " ";
   }

 } //end debugQueue

main.cpp代码为:

#include <iostream>
#include "queueAsArray.h"

using namespace std;

int main()
{
    queueType<int> q1;
    queueType<int> q2;
    queueType<int> q3;
    int x = 5;

    for(int i= 0; i<10; i++) {
        q1.addQueue(i);
    }

    cout << "q1 after being filled up with 10 items" << endl;

    q1.printQueueInfo();

    cout << "Queue contents from front to rear\n\n" << endl;

    q1.debugArray();
    q1.deleteQueue();
    q1.deleteQueue();
    q1.deleteQueue();

    for(int i= 0; i<=20; i){
        i+=5;
        q1.addQueue(i);
    }

    q1.debugArray();
    return 0;
}

是否有函数调用不会再次打印的原因?如果您需要整个类和实现文件,我可以提供。奇怪的是,如果我创建类 q2 的第二个实例化,然后为 q2 构建一个数组,debugQueue 函数会打印该队列。然后我调用重载赋值运算符并执行 q2=q1,然后再次调用 debugQueue 并打印队列的内容。所以我很困惑为什么它会打印第二个队列两次,而不是第一个队列。 有什么想法吗?

最佳答案

看起来你的问题是你正在改变 queueType实例作为打印的一部分。

template <class Type>
void queueType<Type>::debugArray() 
{
  for(queueFront; queueFront<count; queueFront++){
    cout<<"[" << queueFront<<"] ,"<< list[queueFront]<<" ";}
} 

这里是带成员(member)queueFront并向前改变它,直到你到达队列的末尾。这正在改变字段 queueFront而不是指向同一位置的本地。尝试使用本地,它会解决您的问题

for(auto current = queueFront; current < count; current++){
  cout<<"[" << current<<"] ,"<< list[current]<<" ";}
} 

注意:我使用了auto对于类型,因为我不知道 queueFront 的类型.我假设它是 list<int>::iterator但不确定。您可以替换 auto使用正确的类型或保持原样,让编译器推断 current 的类型

关于c++ - 尝试将队列打印为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12981681/

相关文章:

javascript - 不使用数组方法删除数组中的第一个元素

multithreading - 在Grand Central Dispatch中使用 “queues”, “multicore”和 “threads”

c++ - 如何获得粉红噪声的每倍频程功率(使用 Aquila DSP 库)?

java - ArrayList<ArrayList<Integer>> 的总和?

elasticsearch - 使用TRIE具有完成句子中间查询功能的自动完成功能?

java - 迭代集合并删除满足特定条件的项目的快速方法

java - synchronized 关键字没有锁定链表,其他线程仍在从中轮询对象

c++ - 无法理解 C++ STL 中的配对如何工作?

c++ - 从范围生成随机整数

c++ - 什么是 std::pair?