【问题标题】:I need help createing a priority queue in c++ [closed]我需要帮助在 C++ 中创建优先级队列 [关闭]
【发布时间】: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&lt;std::string, int&gt; 作为数据类型传递。除非您的任务是从头开始实际实施,否则我强烈建议您研究heaps
  • 您的代码中有太多的空白需要填补。我只想指出一件事。所有函数中pri 的类型必须是int,而不是T
  • @RSahu 为什么会这样? pri 也可以是 double,我认为它作为模板没有任何问题。
  • @nwp,我写评论后,OP改变了问题。
  • @RSahu 是的,抱歉,我在更改代码时一直在进行更改和编辑

标签: c++ templates queue priority-queue


【解决方案1】:

我会指导您使用 cppreference 获取 std::priority_queue。这应该有助于我思考。以及 wikipedia 上的 Priority Queue 提供了一个很好的实现部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2021-06-29
    • 2013-02-28
    • 1970-01-01
    • 2011-09-15
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多