Topic 63 of 83
Sequence Containers
Overview
Sequence containers store data in a linear manner. `vector` is a dynamic array (the default choice). `list` is a doubly-linked list. `deque` is a double-ended queue.
Syntax
cpp
#include <vector>
#include <list>
#include <deque>
// Vector (Dynamic Array - O(1) back insertion, O(N) front)
std::vector<int> v;
v.push_back(10);
v[0]; // Fast random access
// List (Doubly Linked List - O(1) insertion anywhere, no random access)
std::list<int> l;
l.push_back(10); l.push_front(5);
// Deque (Double Ended Queue - O(1) front/back insertion, fast access)
std::deque<int> dq;
dq.push_back(10); dq.push_front(5);Common Pitfalls
- Using `push_front` on a `vector`. It takes O(N) time because every single element must be shifted right. Use `deque` instead.
Interview Tips
- When to use what: Use `vector` 95% of the time. Use `list` if you have massive amounts of insertions/deletions in the MIDDLE of the sequence. Use `deque` if you need to push/pop at BOTH the front and back.
Real-World Example
Using vector for a dynamic inventory system.
example
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> inventory;
// Add items
inventory.push_back("Sword");
inventory.push_back("Shield");
inventory.push_back("Potion");
// Remove last item
inventory.pop_back();
cout << "Inventory size: " << inventory.size() << endl;
return 0;
}