【发布时间】:2014-05-18 04:27:55
【问题描述】:
我正在尝试创建一个优先级队列程序,其中包含一个字符串作为其数据和数字作为优先级, enqueue("Hello", 3); 以下是我迄今为止所做的,但我很难把所有东西放在一起,任何关于我应该做的不同的事情或帮助我编写程序的帮助将不胜感激。
我认为我应该将队列存储在一个向量中,并以某种方式对里面的数据进行排序以匹配相应的优先级。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <class T1, class T2>
class PriQueue
{
public:
//PriQueue();
void enqueue(T1 str, T2 pri); //Adds to queue
void dequeue(T1 str, T2 pri); //Deletes from queue
void peek(T1 str, T2 pri); //Prints the the first in queue
void size(T1 size); //Prints how many in queue
T1 printQ();
private:
T1 s;
T2 p;
};
template <class T1, class T2>
void PriQueue<T1, T2>::enqueue(T1 str, T2 pri) //Adding an element to the queue
{
this->s = str;
this->p = pri;
}
template <class T1, class T2>
void PriQueue<T1, T2>::dequeue(T1 str, T2 pri) //Removing an element from the front of the queue
{
}
template <class T1, class T2>
void PriQueue<T1, T2>::peek(T1 str, T2 pri) //Returning a value at front of the queue (NOT removing it)
{
}
template <class T1, class T2>
void PriQueue<T1, T2>::size(T1 size) //Returning the number of items in the queue.
{
}
using namespace std;
int main()
{
PriQueue<string, int> que;
que.enqueue("Hello", 3);
que.enqueue("Bye", 2);
que.enqueue("No", 5);
cout << que.printQ() << endl;
return 0;
}
【问题讨论】:
-
您可能应该考虑将
std::priority_queue与自定义comparitor一起使用,并简单地将std::pair<std::string, int>作为数据类型传递。除非您的任务是从头开始实际实施,否则我强烈建议您研究heaps -
您的代码中有太多的空白需要填补。我只想指出一件事。所有函数中
pri的类型必须是int,而不是T。 -
@RSahu 为什么会这样?
pri也可以是double,我认为它作为模板没有任何问题。 -
@nwp,我写评论后,OP改变了问题。
-
@RSahu 是的,抱歉,我在更改代码时一直在进行更改和编辑
标签: c++ templates queue priority-queue