std :: priority_queue比较和队列元素的年龄

时间:2013-09-16 08:25:50

标签: c++ priority-queue

从这里采取http://www.cplusplus.com/reference/queue/priority_queue/

Compare
A binary predicate that takes two elements (of type T) as arguments and returns a bool.
The expression comp(a,b), where comp is an object of this type and a and b are elements in the container, shall return true if a is considered to go before b in the strict weak ordering the function defines.

当编写比较函数时,是否有任何方法可以告诉哪个元素在队列中等待的时间更长?

假设每当要插入一个新元素时都会调用compare函数,'a'将始终是新项,'b'是否已经在队列中?或者它的工作方式不同?

我的想法是这样的:

bool my_class::operator()(const my_class &a, const my_class &b) {
    //Lower priority comes first
    return (a.get_priority() < b.get_priority());
}

当'a'和'b'的优先级相同时,'b'优先,因为它在队列中的时间更长。

感谢您提供有关std :: queue如何工作以及如何实现目标的任何反馈。

2 个答案:

答案 0 :(得分:1)

  

假设每当要插入一个新元素时都会调用compare函数,'a'将始终是新项,'b'是否已经在队列中?或者它的工作方式不同?

正如DietmarKühl在下面所指出的那样,无法保证谓词的参数是否与插入元素的顺序有任何关系。

  

当'a'和'b'的优先级相同时,'b'优先,因为它在队列中的时间更长。

使用类似的东西:

static unsigned long count = 0;
std::priority_queue<std::pair<my_class,unsigned long>> queue;

将项目插入队列时,也插入上一个count并将其递增:

queue.push(std::make_pair(obj, count++));

现在count可以用作“时间戳”,所以只需在compare函数中执行此操作。

class MyComparator{
public:  
  bool operator()(const std::pair<my_class,unsigned long>& a, const std::pair<my_class,unsigned long>& b)  const
    {
       if (a.first == b.first)
          return a.second < b.second;
       return a.first < b.first;
    }
};

这是一个小例子:

#include <queue>
#include <utility>
#include <vector>
#include <iostream>


class MyComparator{
    public:
      bool operator()(const std::pair<int,unsigned long>& a, const std::pair<int,unsigned long>& b)
        {
           if (a.first == b.first)
              return b.second  < a.second;
           return a.first < b.first;
        }
    };

unsigned long count = 0;
int main()
{
        std::priority_queue<std::pair<int,unsigned long>, std::vector<std::pair<int, unsigned long> >, MyComparator> queue;

        queue.push(std::make_pair(4, count++));
        queue.push(std::make_pair(4, count++));
        queue.push(std::make_pair(5, count++));
        queue.push(std::make_pair(3, count++));

        while(queue.size() > 0)
        {
                std::cout << "[" << queue.top().first << ", " << queue.top().second << "]" << std::endl;
                queue.pop();
        }

        return 0;

}

输出:

[5, 2]
[4, 0]
[4, 1]
[3, 3]

答案 1 :(得分:0)

保留对象的时间戳,并在将对象插入队列时进行设置。然后只使用该时间戳作为条件的一部分进行比较。