For the std::priority_queue I assumed that the first template parameter specified the type and the second should be a container of that type. Example:
priority_queue<int, vector<int>> someQueue;
However, the following code compiles and seems to run fine:
class SomeClass
{
};
int main()
{
priority_queue <SomeClass, vector<int>> pq;
int x = 9;
pq.push(x);
int t = pq.top();
cout << t << endl;
pq.pop();
return 0;
}
Is the above code invalid (i.e. giving UB)?
If it is valid - what is the first template parameter (i.e. someClass
) used for in the priority_queue.
Suitable underlying container classes for priority_queue include deque Class and the default vector Class or any other sequence container that supports the operations of front , push_back , and pop_back and a random-access iterator.
A priority queue in c++ is a type of container adapter, which processes only the highest priority element, i.e. the first element will be the maximum of all elements in the queue, and elements are in decreasing order.
class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> > class priority_queue; A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.
priority_queue::top() top() function is used to reference the top element of the priority queue. The top (by default) element is the largest element in C++ STL. However in other programming languages like java, by default a min heap is created and the top() gives the minimum element.
Freshly voted into the working paper in Jacksonville, via LWG issue 2566:
The first template parameter
T
of the container adaptors shall denote the same type asContainer::value_type
.
Writing std::priority_queue<SomeClass, std::vector<int>>
accordingly results in undefined behavior.
In the C++11 specification the section about std::priority_queue
is §23.6.4. In it the first template argument is simply the default type used for the container and nothing else.
The actual value type is taken from the container.
The class is declared as
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
[Taken from this reference]
That declaration show how, when and where the first template argument is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With