C++优先队列,逻辑错误,想不通

标签 c++ priority-queue

我正在用 C++ 实现一个简单的优先级队列。

但是当它运行时,它会打印出乱码。 我是否以某种方式试图在我的代码中访问数组中的无效条目?

下面是代码。

此外,我的“删除”功能是否以某种方式无法正常工作?从概念上讲,我是否应该将 null 放入第一个条目并返回刚刚删除的所有内容?

谢谢。

[优先级.h]

#ifndef Priority_h
#define Priority_h


class Priority
{
    public:
        Priority(void);
        Priority(int s);
        ~Priority(void);

        void insert(long value);
        long remove();
        long peekMin();
        bool isEmpty();
        bool isFull();

        int maxSize;
        long queArray [5];
        int nItems; 

    private:

};

#endif

[优先级.cpp]

#include <iostream>
#include <string>
#include <sstream>
#include <stack>
#include "Priority.h"

using namespace std;

Priority::Priority(void)
{

}

Priority::Priority(int s)
{
    nItems = 0;
}

Priority::~Priority(void)
{

}

void Priority::insert(long item)    
{
      int j;

      if(nItems==0)                         // if no items,
            {
            queArray[0] = item; nItems++;
            }// insert at 0
      else                                // if items,
         {
         for(j=nItems-1; j=0; j--)         // start at end,
            {
            if( item > queArray[j] )      // if new item larger,
               queArray[j+1] = queArray[j]; // shift upward
            else                          // if smaller,
               break;                     // done shifting
            }  // end for
         queArray[j+1] = item;            // insert it
         nItems++;
         }  // end else (nItems > 0)

}

long Priority::remove()             
{ 
    return queArray[0];
}

long Priority::peekMin()            
{ 
    return queArray[nItems-1]; 
}

bool Priority::isEmpty()         
{ 
    return (nItems==0);
}

bool Priority::isFull()          
{
    return (nItems == maxSize); 
}

int main ()
{
      Priority thePQ; 
      thePQ.insert(30);
      thePQ.insert(50);
      thePQ.insert(10);
      thePQ.insert(40);
      thePQ.insert(20);

      while( !thePQ.isEmpty() )
         {
         long item = thePQ.remove();
         cout << item << " ";  // 10, 20, 30, 40, 50
         }  // end while
      cout << "" << endl;

    system("pause");
}

最佳答案

这是一个错误:

     for(j=nItems-1; j=0; j--)         // start at end,
                      ^ this is assignment, not comparison.

我也不相信

     queArray[j+1] = item;            // insert it

最后,您的默认构造函数无法初始化 nItems

可能还有更多错误,但我会就此打住。

关于C++优先队列,逻辑错误,想不通,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15531993/

相关文章:

c++ - 在对象 vector 上调用成员函数

c# - 有限并发级别的任务调度程序(具有任务优先级)处理包装任务

c++ - Dalvik 对 native C++ 代码性能的影响?

c++ - 在字符串常量之前预期为 ‘,’ 或 ‘...’

c++ - EDSDK 3.6 macOS - 32 位与 64 位和链接错误

java - 最佳方法: tree set structure vs thread pool executor

algorithm - d-heap 如何在 O(log n) 中执行插入和删除?

Android自定义来电接听应用

java - 如何以编程方式在 ActiveMQ 中启用优先级队列?

c++ - 为什么通过地址传递大括号初始化的临时变量需要显式转换为 MSVS 中的相同类型