Accessing Underlying Container of STL Container Adaptors
Container adaptors in the C Standard Template Library (STL), such as stack, queue, and priority_queue, provide a convenient interface on top of underlying containers like deque or vector. However, obtaining a reference to the underlying container, as needed for customized operations, can be challenging.
Is There a Standard Way?
No, there is no standard method to directly access the underlying container from these adaptors. The _Get_container() method mentioned is not part of the C standard and may vary depending on the implementation.
Common Workaround
One common workaround involves using template specialization, as follows:
<code class="cpp">template <class Type> struct ContainerAdapter { static Type& container(const Type& adapter) { return adapter; // Assumes underlying container is of the same type } };</code>
By specializing this template for each specific adaptor type, we can access the underlying container. For example:
<code class="cpp">template <> struct ContainerAdapter<std::stack<int>> { static std::deque<int>& container(const std::stack<int>& stack) { return stack.*&stack::_deque; // Internal implementation hack } };</code>
Custom Implementation for priority_queue
In the case of priority_queue, a similar approach can be implemented using a struct template:
<code class="cpp">template <class T, class S, class C> struct PriorityQueueAdapter { static S& container(priority_queue<T, S, C>& pq) { // Use a type trick to access private member struct Inner : private priority_queue<T, S, C> { static S& container(priority_queue<T, S, C>& pq) { return pq.*&Inner::c; } }; return Inner::container(pq); } };</code>
Official Documentation
The official documentation for the C Standard Library can be found on the ISO/IEC website: https://www.iso.org/standard/74983.html
The above is the detailed content of How Can I Access the Underlying Container of an STL Container Adaptor?. For more information, please follow other related articles on the PHP Chinese website!