如何使用优先级队列STL对象?

时间:2013-10-23 07:38:16

标签: c++ stl

class Person
{
public:
    int age;
};

我想将Person类的对象存储在优先级队列中。

priority_queue< Person, vector<Person>, ??? >

我想我需要为比较事物定义一个类,但我不确定。

另外,当我们写作时,

priority_queue< int, vector<int>, greater<int> > 

如何做得更好?

5 个答案:

答案 0 :(得分:100)

在这种情况下,您需要为存储在队列中的类型Person提供有效的严格弱排序比较。默认设置是使用std::less<T>,它会解析为等同于operator<的内容。这依赖于它自己的存储类型。所以,如果你要实施

bool operator<(const Person& lhs, const Person& rhs); 

它应该没有任何进一步的改变。实施可能是

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

如果该类型没有自然的“小于”比较,那么提供自己的谓词更有意义,而不是默认的std::less<Person>。例如,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

然后像这样实例化队列:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

关于使用std::greater<Person>作为比较器,这将使用等效的operator>,并且具有创建优先级为WRT的队列的默认情况。它需要存在operator>,可以在两个Person个实例上运行。

答案 1 :(得分:44)

您可以编写比较器类,例如:

struct CompareAge {
    bool operator()(Person const & p1, Person const & p2) {
        // return "true" if "p1" is ordered before "p2", for example:
        return p1.age < p2.age;
    }
};

并将其用作比较器参数:

priority_queue<Person, vector<Person>, CompareAge>

使用greater给出与默认less相反的顺序,这意味着队列将为您提供最低值而不是最高值。

答案 2 :(得分:18)

优先级队列是一种抽象数据类型,它捕获容器的概念,该容器的元素具有附加到它们的“优先级”。优先级最高的元素始终显示在队列的前面。如果删除该元素,则下一个最高优先级元素前进到前面。

C ++标准库定义了一个类模板priority_queue,其操作如下:

推送:将元素插入到prioity队列中。

顶部:从优先级队列返回(不删除)优先级最高的元素。

pop :从优先级队列中删除优先级最高的元素。

size :返回优先级队列中的元素数。

:根据优先级队列是否为空,返回true或false。

以下代码段显示了如何构造两个优先级队列,一个可以包含整数,另一个可以包含字符串:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

以下是优先级队列使用的示例:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
{
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("fox");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << pq.top() << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string
    }

    return 0;
}

该程序的输出是:

the quick
the lazy dog
jumped over
fox

由于队列遵循优先级规则,因此字符串将从最高优先级打印到最低优先级。

有时需要创建一个优先级队列来包含用户定义的对象。在这种情况下,优先级队列需要知道用于确定哪些对象具有最高优先级的比较标准。这是通过一个函数对象完成的,该函数对象属于一个重载operator()的类。 overloaded()充当&lt;为了确定优先事项。例如,假设我们要创建一个优先级队列来存储Time对象。 Time对象有三个字段:小时,分钟,秒:

struct Time {
    int h; 
    int m; 
    int s;
};

class CompareTime {
    public:
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
}

根据上述比较标准存储时间的优先级队列定义如下:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59
};

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2)
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
};

int main()
{
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)
       pq.push(t[i]);

    while (! pq.empty()) {
       Time t2 = pq.top();
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;
       pq.pop();
    }

    return 0;
}

该程序打印从最晚到最早的时间:

5  16  13
5  14  20
3   2  40
3   2  26

如果我们希望最早的时间具有最高优先级,我们会像这样重新定义CompareTime:

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
    {
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;
    }
};

答案 3 :(得分:2)

这段代码可以帮助..

#include <bits/stdc++.h>
using namespace std;    

class node{
public:
    int age;
    string name;
    node(int a, string b){
        age = a;
        name = b;
    }
};

bool operator<(const node& a, const node& b) {

    node temp1=a,temp2=b;
    if(a.age != b.age)
        return a.age > b.age;
    else{
        return temp1.name.append(temp2.name) > temp2.name.append(temp1.name);
    }
}

int main(){
    priority_queue<node> pq;
    node b(23,"prashantandsoon..");
    node a(22,"prashant");
    node c(22,"prashantonly");
    pq.push(b);
    pq.push(a);
    pq.push(c);

    int size = pq.size();
    for (int i = 0; i < size; ++i)
    {
        cout<<pq.top().age<<" "<<pq.top().name<<"\n";
        pq.pop();
    }
}

输出:

22 prashantonly
22 prashant
23 prashantandsoon..

答案 4 :(得分:0)

我们可以定义用户定义的比较器:。下面的代码对您有所帮助。

代码段:

#include<bits/stdc++.h>
using namespace std;

struct man
{
  string name;
  int priority; 
};

class comparator
{
 public:
   bool operator()(const man& a, const man& b)
   {
        return a.priority<b.priority;
   }
};

int main()
{
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)
   {
     cin>>arr[i].name>>arr[i].priority;
     pq.push(arr[i]);
   }

   while (!pq.empty())
   {
     cout<<pq.top().name<<" "<<pq.top().priority;
     pq.pop();
     cout<<endl;
   }
   return 0;
}

输入:

  蝙蝠侠2
  悟9
  马里奥4

输出

  

悟空9
  马里奥4
  蝙蝠侠2

相关问题