C++ 优先级队列,逻辑错误,无法弄清楚
C++ Priority Queue, logical error, can't figure out
我正在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"方法实际上并没有删除任何东西——它只是返回第一个元素——但是它对数组本身没有做任何事情。
编辑说您的插入方法需要一些工作-它可能会或可能不会在数组的末尾写入,但它肯定是令人困惑的,因为它正在做什么
尝试在构造函数中初始化队列数组。
相关文章:
- 写一个分数类,我无法弄清楚这些错误
- 分段错误(核心转储)但无法弄清楚
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 我无法弄清楚"对Winmain@16错误的未定义引用"
- 我的程序不断抛出编译错误,我无法弄清楚为什么会发生错误
- 无法弄清楚错误来自哪里(调试器说分段错误)
- 无法弄清楚此错误的含义
- 我在用c ++编程时一直遇到LNK2005错误,我似乎无法弄清楚问题是什么
- 我无法弄清楚我的程序的问题,即使我已经查看了错误日志消息
- C 向量下标超出范围,没有逻辑错误,无法弄清楚
- 运行时检查失败#2 - 变量周围的堆栈'myArray'已损坏.- 似乎无法弄清楚如何删除此错误
- 我无法弄清楚此访问冲突错误.有人可以在这里帮助我吗?
- 一直试图调试此加密算法.无法弄清楚什么是错误
- 链接错误:无法弄清楚如何将数组作为函数参数传递/接收
- 在 GetTransfer 之后,我在帐户 1 收到未分配变量错误。我无法弄清楚我搞砸了什么逻辑错误
- C++ 简单的指针错误无法弄清楚为什么?
- 我一直收到错误LNK2019,似乎无法弄清楚如何解决它
- 无法弄清楚为什么我的程序在 spoj 上给出运行时错误而不是在 ideone 上给出运行时错误的原因
- 我怎样才能弄清楚这个分段错误发生的位置和原因
- C ++中的构建错误,未定义的符号,在这里尝试了其他答案,无法弄清楚