Introduction to Stacks using std::stack

Changing the underlying container of std::stack

What are some reasons I might want to change std::stack's underlying container to something other than std::deque?

Illustration representing computer hardware

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:

  1. Memory Usage: If memory is a constraint and you have a large number of small stacks, using 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.
  2. Consistency: If your code extensively uses a particular container type, using the same type for your stacks can make the code more consistent and potentially easier to understand and maintain.
  3. Specific Operations: Although rare, if you need to perform operations on the stack that the underlying container doesn't support efficiently, changing the container can be beneficial. For example, if you frequently need to splice elements from one stack into another, using 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.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved