Can you explain the differences between std::deque and std::list containers in C++?
sobes.tech AI
Answer from AI
std::deque (double-ended queue) and std::list are two different containers in C++, designed for storing sequences of elements, but with different internal organization and characteristics.
-
std::deque is a sequence implemented as a set of memory blocks, allowing efficient addition and removal of elements from both ends. It provides fast access by index (amortized O(1) time). It supports random access to elements.
-
std::list is a doubly linked list, where each element stores pointers to the previous and next elements. It allows efficient insertion and deletion of elements anywhere in the list (O(1) time with an iterator), but does not support random access (access by index is O(n)).
Main differences:
| Characteristic | std::deque | std::list |
|---|---|---|
| Internal structure | Array of blocks | Doubly linked list |
| Access by index | Fast (O(1)) | Slow (O(n)) |
| Insertion/deletion | Fast at ends, slow in middle | Fast anywhere (with iterator) |
| Memory usage | More compact | Extra memory for pointers |
Example:
#include <iostream>
#include <deque>
#include <list>
int main() {
std::deque<int> d = {1, 2, 3};
d.push_front(0); // Fast addition at the front
std::cout << "deque[2]: " << d[2] << "\n"; // Fast index access
std::list<int> l = {1, 2, 3};
auto it = l.begin();
std::advance(it, 1);
l.insert(it, 10); // Fast insertion in the middle
for (int x : l) std::cout << x << " ";
}
The choice depends on the task: if you need fast random access and operations at the ends — deque, if fast insertion/deletion in the middle is important — list.