-
c++ stl priority queue
hi...
i wanted to implement piority queues using c++ stl....
i want to extract both min and max elemnts (compute with the extracted value as well a s pop them out of queue)
for eg:
std:priority_queue<int> q;
q.push(i);
q.push(j);.............
i am able to pop the largest since front elemnet is largest...
well i want to pop the smallest elemnts as well..i also want the samallest and largest elemnt to be stored in a temp variable so as to compute sumthng else...
can u guide me on how do i get there
-
If you want the min and the max, then you don't have a priority queue. Maybe you want a set or a map instead.
-
but for that is what priority queue is meant for ...am i right....
the queue is automatically arranged according to the required spec..
i dont want to sort in manually as it ll consume a lot of time.....
extracting min and max from this ll save running time....
-
A set automatically stores it's values from low to high. A map stores it's values according to the key values, low to high (so you can have weights different from the values; if you need more than one item with the same weight, then I guess you need a multimap). Both of them allow access to both the low and the high, unlike a priority queue, which only allows access to the highest value.
-
thanks....can u give me an example on how do i implement it
-
If I'm not mistaken, a priority_queue is not just a sorted container (every operation would have a bad complexity). It is based on a heap structure. A heap cannot be a max-heap and a min-heap at the same time. It is easy to get the max item and pop it, but finding the min item would require a linear search in the bottom levels, and popping a min item would require re-heapifying the structure.
-
Why implement them? They're already there, as std::set and std::map and std::multimap.
-
well i will have duplicating elements too...so i guess set wont work(just now googled...am i right)
well think i can use mutiset...but what member function ll return min and max....
wil map ll be more comfortable....
well i want to know the member functions to take care rather than explicit sorting....
-
.begin() gives the first element of a container. .end() gives one past the end; you can use .rbegin() to get the actual last element I would guess.
I have no idea what you're asking about sorting.