Home > Backend Development > C++ > body text

How to Access the Underlying Containers in STL Container Adaptors?

Linda Hamilton
Release: 2024-11-02 23:02:30
Original
436 people have browsed it

How to Access the Underlying Containers in STL Container Adaptors?

Accessing Underlying Containers in STL Container Adaptors

In C , STL container adaptors layer additional functionality over existing containers. However, accessing the underlying container in these adaptors may be desirable for certain operations.

Method for Stack and Queue

For stack and queue, there is a non-standard method called _Get_container() that can retrieve the underlying container. However, this method is not part of the standard and its availability may vary across implementations.

Method for Priority_queue

Unfortunately, there is no standard method to access the underlying container of a priority_queue.

Alternative Approach

One alternative approach for all three container adaptors is to use a privately derived class with access to the underlying container. For example, for a priority_queue:

<code class="cpp">template <class T, class S, class C>
S&amp; Container(priority_queue<T, S, C>&amp; q) {
    struct HackedQueue : private priority_queue<T, S, C> {
        static S&amp; Container(priority_queue<T, S, C>&amp; q) {
            return q.*&amp;HackedQueue::c;
        }
    };
    return HackedQueue::Container(q);
}</code>
Copy after login

This approach allows access to the underlying container through the Container() function.

Standard Library Documentation

Official documentation for the C standard library can be found at the following locations:

  • [C Reference](https://en.cppreference.com/w/)
  • [STL Tutorial](https://www.learncpp.com/cpp-tutorial/the-c-standard-library-48-stl/)

Clarification

The user's goal is to print the contents of a one-value container using a generic function. This can be achieved by accessing the underlying container, which contains the actual data.

The above is the detailed content of How to Access the Underlying Containers in STL Container Adaptors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!