标签:oid new img clu public 入队 自动 mem eem
优先级队列和普通队列并没有特大的不同之处,不一样的地方是,优先级队列的元素具有优先级之分。优先级高的元素在入队的时候应该放在队列前面。我下面实现的优先级队列元素的优先级由其数值大小决定。数值越小,优先级越高。ps:这和按一定规则排序好队列没啥区别啊。
实现如下
//header.h
#ifndef _HEADER_H
#define _HEADER_H
#include<iostream>
#include<assert.h>
#include<string.h>
using namespace std;
const int DefaultPQSize = 50;
template<class T>
class PQueue
{
private:
T *pqelements;
int count;
int maxSize;
void adjust();
public:
PQueue(int sz = DefaultPQSize);
~PQueue(){delete[]pqelements;}
bool Insert(const T& x);
bool RemoveMin(T& x);//得到权值最大的元素,即取队头
bool getFront(T& x) const;//得到权值最小的元素,也就是取队尾
void makeEmpty();//置空数组
bool IsEmpty() const{return (this->count==0 ? true : false);}
bool IsFull() const{return (this->maxSize==this->count ? true : false);}void print() const;
};
template<class T>
void PQueue<T>::makeEmpty()
{
//memset((void)*this->pqelements, ‘0‘, sizeof(T)*this->count);很奇怪为啥不让用memset,用了就出错。。
for(int i=0; i<this->count; ++i)
this->pqelements[i] = 0;
this->count = 0;
}
template<class T>
bool PQueue<T>::getFront(T& x) const
{
if(!this->IsEmpty())
{
x = this->pqelements[this->count-1];
return true;
}
return false;
}
template<class T>
bool PQueue<T>::RemoveMin(T& x)
{
if(!this->IsEmpty())
{
x = this->pqelements[0];
for(int i=0; i<this->count-1; ++i)
this->pqelements[i] = this->pqelements[i+1];
--this->count;
return true;
}
return false;
}
template<class T>
PQueue<T>::PQueue(int sz):maxSize(sz), count(0)
{
pqelements = new T[maxSize];
assert(pqelements != NULL);
}
template<class T>
bool PQueue<T>::Insert(const T& x)
{
if(this->IsFull())
{
T *newspace = new T[maxSize+DefaultPQSize];
if(newspace == NULL)
return false;
this->maxSize = maxSize + DefaultPQSize;
memcpy((void*)newspace, (void*)this->pqelements, sizeof(T)*this->count);
}
this->pqelements[this->count++] = x;
adjust();
}
template<class T>
void PQueue<T>::adjust()
{
if(this->count==0)
return;
else
{
for(int i=0; i<this->count-1; ++i)
for(int j=i+1; j<this->count; ++j)
{
if(this->pqelements[i]>this->pqelements[j])
{
this->pqelements[i] = this->pqelements[i] + this->pqelements[j];
this->pqelements[j] = this->pqelements[i] - this->pqelements[j];
this->pqelements[i] = this->pqelements[i] - this->pqelements[j];
}
}
}
return;
}
template<class T>
void PQueue<T>::print()const
{
int i = 0;
while(i!=this->count)
{
cout<<this->pqelements[i++]<<" ";
}
cout<<endl;
}
#endif
#include"header.h"
int main()
{
PQueue<int> pq;
for(int i=0; i<100; ++i)//插入100个元素以检验是否可自动扩容
pq.Insert(i);
pq.print();
int i = 0;
if(pq.getFront(i))
cout<<i<<endl;
if(pq.RemoveMin(i))
pq.print();
cout<<i<<endl;
pq.makeEmpty();
pq.print();
return 0;
}
结果如下
标签:oid new img clu public 入队 自动 mem eem
原文地址:https://www.cnblogs.com/area-h-p/p/11305190.html