By default, std::stack
uses std::deque
as its underlying container. However, you can change this to other container types that meet certain requirements. There are a few potential reasons to do this:
std::vector
as the underlying container can be more memory-efficient. This is because std::deque
allocates memory in chunks, which can lead to some wasted space, while std::vector
uses contiguous memory.std::list
would make this operation efficient.Here's an example of declaring a stack with a different underlying container:
#include <stack>
#include <vector>
int main() {
std::stack<int, std::vector<int>> s;
// operations on s will use std::vector
}
However, it's important to note that the underlying container must support certain operations (back()
, push_back()
, pop_back()
, and emplace_back()
) for std::stack
to work correctly. Most standard containers like std::vector
, std::list
, and std::deque
support these.
Also, changing the underlying container is an optimization that should be done judiciously based on profiling and performance requirements. For most use cases, the default std::deque
is efficient and flexible enough.
Answers to questions are automatically generated and may not have been reviewed.
std::stack
An introduction to the stack data structure, and the standard library implementation - std::stack