initialization for STL priority queue

前端 未结 2 1460
时光说笑
时光说笑 2021-02-10 00:57

I\'m still confused about priority queue in STL. Here is the objective I wanna achieve, say: I have a structure called Record, which contains a string word and a int counter. Fo

2条回答
  •  忘掉有多难
    2021-02-10 01:14

    std::priority_queue cannot magically know how to sort the elements. You must tell it how to do so. The way to do that is to give priority_queue a functor type which, when called with two objects, returns whether the first argument is "less than" the second, however you want to define that. This functor is a template parameter to the priority_queue.

    The default parameter is std::less, which requires that type (what you're putting in the queue) has an overloaded operator<. If it doesn't, then you either have to provide one or you have to provide a proper comparison functor.

    For example:

    struct Comparator
    {
      bool operator()(const Record& lhs, const Record& rhs)
      {
        return lhs.count>rhs.count;
      }
    };
    
    std::priority_queue, Comparator> myQ;
    

    The reason that doesn't work with just an overload on Record is because you didn't tell the priority_queue that it was the comparison. Also, the type used for comparison needs to be default constructable, so that the priority_queue can create and destroy the objects at will.

    Though to be honest, I don't know why you don't just stick them in a std::set if you want to sort them. Or just run std::sort on the std::vector of items.

提交回复
热议问题