Limit size of stl stack object

Is there any size limit for a std::stack ?

I use std::stack<std::pair<int,std::string>> as my stack, and when the number of entries exceeds about 1 million, I get a runtime error.

Is this due to the std::stack size limit?

+4
source share
2 answers

std::stack is a container adapter. This is just the front for another container that makes it look like a stack. Consider that std::vector can be thought of as a stack if you replace the name push with push_back and the name pop with pop_back . Thus, any size restrictions or similar values ​​will be the result of a backup container, not std::stack .

The default default container for std::stack is std::deque ( N3376 23.6.5.2 [stack.defn] ). The standard requires that std::deque provide a member function max_size ( N3376 23.3.3.1 [deque.overview]/2 ), which tells you the maximum number of elements that std::deque can hold in accordance with implementation restrictions. It will usually look like std::numeric_limits<std::deque<t>::size_type>::max() .

However, it is more likely that you either click on the limits of the computer’s memory or find an error elsewhere in the application, causing a runtime error.

+5
source

The base container adapter container container is std::stack , located in the protected section, and can be obtained by the name c (from derived classes using the fully qualified name or by introducing classes into the namespace using using derective). The default main container is std::deque . std::deque , std::list or std::vector . They all provide the member function max_size() , returning the maximum size that can be allocated. Authoritative source WRT max_size() The member function of the specified containers indicated:

Notes

This value is usually equal to std :: numeric_limits :: max () and reflects the theoretical limit on the size of the container. At run time, the size of the container may be limited to a value less than max_size () by the amount of available RAM.

So, the return value max_size() smart implementation can rely on the RAM available for hosting.

To access std::stack<>::c.max_size() , you should write a derivative from the std::stack<> class as follows:

 #include <iostream> #include <stack> #include <cstdlib> template< typename type > struct my_stack : std::stack< type > { using base = std::stack< type >; using base::base; using base::operator =; std::size_t max_size() const { return base::c.max_size(); } }; int main() { my_stack< int > s; std::cout << s.max_size() << std::endl; return EXIT_SUCCESS; } 
0
source

All Articles