Home >Backend Development >C++ >How can I access the underlying container of an STL priority_queue?
Accessing the Underlying Container of STL Container Adaptors
The Standard Template Library (STL) provides container adaptors like stack, queue, and priority_queue, which offer a convenient interface while providing an abstracted layer over the underlying container. However, there is a lack of a standardized method to access the underlying container in these adaptors.
Current Implementation
In some implementations of the STL, such as Microsoft's Visual Studio 2008, a non-standard method called _Get_container() is available for stack and queue. However, no such method exists for priority_queue.
Accessing the Underlying Container in priority_queue
Despite the lack of a standard method, a workaround has been devised:
<code class="cpp">template <class T, class S, class C> S& Container(priority_queue<T, S, C>& q) { struct HackedQueue : private priority_queue<T, S, C> { static S& Container(priority_queue<T, S, C>& q) { return q.*&HackedQueue::c; } }; return HackedQueue::Container(q); }</code>
This code defines a helper function Container() that utilizes a nested private class HackedQueue to access the underlying container c.
Usage
With this workaround, you can access the underlying container of priority_queue as follows:
<code class="cpp">priority_queue<SomeClass> pq; vector<SomeClass>& tasks = Container(pq);</code>
Official Documentation
The official documentation for the STL can be found at the following link:
Conclusion
While there is no standard method to access the underlying container of STL container adaptors, the workaround provided offers a solution for priority_queue specifically. For stack and queue, the non-standard _Get_container() method can be utilized if available.
The above is the detailed content of How can I access the underlying container of an STL priority_queue?. For more information, please follow other related articles on the PHP Chinese website!