How std::deque is implemented internally

How does a std::deque store its elements in memory?

Under the hood, a std::deque is typically implemented as a sequence of contiguous chunks of memory, sometimes called "blocks" or "pages".

Each block holds a fixed number of elements. The deque maintains a dynamic array of pointers, where each pointer points to one of these blocks.

This structure provides several advantages:

  1. It allows efficient insertion and deletion at both ends of the deque. Only the pointers need to be adjusted, no elements need to be moved.
  2. It provides random access to elements. To access an element, the deque calculates which block it's in and the offset within that block.
  3. It avoids the reallocation overhead of std::vector when inserting at the front.

However, this structure is not as cache-friendly as a std::vector's contiguous memory, which can impact iteration and random access performance.

Here's a simplified example of how a deque might be implemented:

template <typename T>
class Deque {
  T** blocks_;
  size_t frontBlock_;
  size_t backBlock_;
  // ...

 public:
  T& operator[](size_t index) {
    size_t block =
      frontBlock_ + (index / blockSize);
    size_t offset = index % blockSize;
    return blocks_[block][offset];  
  }
  // ...
};

Double-Ended Queues using std::deque

A guide to double-ended queues - a structure that behaves like a vector, specialised for manipulating objects at the edges of the collection

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Performance differences between std::vector and std::deque
When should I use a std::deque instead of a std::vector for optimal performance?
Exception safety of std::deque operations
Which std::deque operations are exception-safe?
Benefits of using emplace over insert
What are the advantages of using emplace_front() or emplace_back() instead of push_front() or push_back()?
Iterator invalidation rules for std::deque
When do std::deque operations invalidate iterators?
Thread safety of std::deque
Is std::deque thread-safe? Can multiple threads access a deque concurrently?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant