[英]stl priority queue based on lower value first
I have a problem with stl priority queue.I want to have the priority queue in the increasing order,which is decreasing by default.Is there any way to do this in priority queue. 我对stl优先级队列有问题。我想让优先级队列按升序排列,默认情况下按降序排列。是否有任何方法可以在优先级队列中执行此操作。
And what is the complexity of building stl priority queue.If i use quick sort in an array which takes O(nlgn) is its complexity is similar to using priority queue??? 构建stl优先级队列的复杂性是什么?如果我在采用O(nlgn)的数组中使用快速排序,那么它的复杂性类似于使用优先级队列?
Plz someone ans.Advanced thanx. 请某人回答。高级thanx。
priority_queue
has template parameters that specify the container type and the comparison to use for ordering. priority_queue
具有模板参数,这些参数指定容器类型和用于订购的比较。 By default, the comparison is less<T>
; 默认情况下,比较为
less<T>
; to get the opposite ordering, use priority_queue<T, vector<T>, greater<T>>
. 要获得相反的顺序,请使用
priority_queue<T, vector<T>, greater<T>>
。
Insertion into a priority queue takes logarithmic time, so building a queue of N
items has complexity O(N logN)
, the same as building and sorting a vector. 插入优先级队列需要花费对数时间,因此构建
N
项目的队列的复杂度为O(N logN)
,与构建和排序向量相同。 But once it's built, insertion into the priority queue is still logarithmic, while insertion into a sorted vector is linear. 但是,一旦构建完成,插入优先级队列仍然是对数的,而插入排序向量中则是线性的。
使用类型
priority_queue<T, vector<T>, greater<T> >
Use a different comparator as the 3rd template argument of std::priority_queue
. 使用其他比较器作为
std::priority_queue
的第三个模板参数。
priority_queue is a container adaptor that works on any sequence you define. priority_queue是一个容器适配器,可用于您定义的任何序列。 The performance of insertion is equal to the
std::push_heap
operation and takes logarithmic time. 插入的性能等于
std::push_heap
操作,并且需要对数时间。 So the complexity to sorting after all insertions are done isn't equal. 因此,在完成所有插入操作后进行排序的复杂性并不相同。 If you insert a fixed amount and work the queue afterwards a
vector
and a single sort
could be more efficient. 如果您插入一个固定的数量,然后再处理队列,则
vector
和单一sort
可能会更有效。
您只需将值乘以-1就可以将其乘以-1,这样它将以与实际默认顺序不同的相反顺序存储...并在检索数据以使其实际形式时再次将值乘以-1。
Replace T bellow with variable type. 用可变类型替换T波纹管。 You will get your work done
您将完成工作
priority_queue<T, vector<T>, greater<T> > PQ;
As example for int type variable you can write it like this: 作为int类型变量的示例,您可以这样编写:
priority_queue<int, vector<int>, greater<int> > Q;
You can use comparator class/struct to achieve the same in priority queue. 您可以使用比较器类/结构在优先级队列中实现相同的目的。
class CompareHeight
{
public:
bool operator()(int &p1, int &p2)
{
return p1 > p2;
}
};
Now declare the priority queue as 现在将优先级队列声明为
priority_queue<int, vector<int>, CompareHeight> pq;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.