C++ 优先级队列,逻辑错误,无法弄清楚

C++ Priority Queue, logical error, can't figure out

本文关键字:弄清楚 错误 优先级 队列 C++      更新时间:2023-10-16

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

然而,当它运行时,它打印出乱码。我是否试图在我的代码中访问数组中的无效条目?

代码如下:

也,是我的"删除"函数不知何故没有做它的工作?从概念上讲,我是否应该将null放入第一个条目并返回刚刚删除的内容?

谢谢。[Priority.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
[Priority.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.

我也不相信

中没有一个off-by- 1错误。
     queArray[j+1] = item;            // insert it

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

可能还有其他错误,我就讲到这里。

我同意这里的其他答案,但我想补充这一点:

你的"Remove"方法实际上并没有删除任何东西——它只是返回第一个元素——但是它对数组本身没有做任何事情。

编辑说您的插入方法需要一些工作-它可能会或可能不会在数组的末尾写入,但它肯定是令人困惑的,因为它正在做什么

尝试在构造函数中初始化队列数组。

相关文章: