Reputation: 149
Is there any limit on the size of a std::stack
?
I am using a std::stack<std::pair<int,std::string>>
as my stack, and when the number of entries exceeds roughly 1 million, I am getting a runtime error.
Is this due to a restriction on the size of std::stack
?
Upvotes: 4
Views: 3496
Reputation: 16681
Underlying container of std::stack
container adapter placed in protected
section and can be accessed by name c
(from derived classes by means of full qualificated name or by introducing into class namespace using using
derective).
Default underlying container is std::deque
. std::deque
, std::list
or std::vector
. All of them provides max_size()
member function, returning maximum size avaliable to allocate yet.
Authoritative source WRT max_size()
member function of the mentioned containers said:
Notes
This value is typically equal to std::numeric_limits::max(), and reflects the theoretical limit on the size of the container. At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available.
So, returning value of max_size()
's smart implementation can rely on RAM avaliable to allocate.
To access std::stack<>::c.max_size()
one should write a derived from std::stack<>
class as following:
#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;
}
Upvotes: 0
Reputation: 106530
std::stack
is a container adapter. It is merely a front for some other container, that makes it look like a stack. Consider that std::vector
can be treated like a stack if you replace the name push
with push_back
and the name pop
with pop_back
. Thus, any size limits or similar are going to be the result of the backing container, not std::stack
.
The default backing container for std::stack
is std::deque
(N3376 23.6.5.2 [stack.defn]
). The standard requires that std::deque
provide a max_size
member function (N3376 23.3.3.1 [deque.overview]/2
), which tells you the maximum number of elements that std::deque
can hold according to implementation limits. This will typically be something like std::numeric_limits<std::deque<t>::size_type>::max()
.
However, it is more likely that you are either running into machine memory limits, or have some bug elsewhere in your application causing the runtime error.
Upvotes: 5