Home  >  Article  >  Backend Development  >  How can I access the underlying container of an STL priority_queue?

How can I access the underlying container of an STL priority_queue?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 06:21:02498browse

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&amp; Container(priority_queue<T, S, C>& q) {
    struct HackedQueue : private priority_queue<T, S, C> {
        static S&amp; Container(priority_queue<T, S, C>& q) {
            return q.*&amp;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:

  • [C : Standard Template Library](https://en.cppreference.com/w/cpp/container)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn