Loading lessons...
Sequence Containers: vector, list and deque
Sequence Containers: vector, list and deque
A sequence container keeps its elements in a linear order: the order in which they were inserted. The STL provides three: vector (a dynamic array), list (a doubly linked list) and deque (a double-ended queue). The vector is by far the most used container in C++ and is named separately in the IPU syllabus, so it gets the most attention here.
1. The vector Container
A vector is a dynamic array: its elements are stored in contiguous memory like an ordinary array, but it grows automatically when elements are added. It is declared in <vector>.
| Feature | Array int a[10] | vector<int> v |
|---|---|---|
| size | fixed at compile time | grows and shrinks at run time |
| knows its own size | no | yes: v.size() |
can be copied/assigned with = | no | yes |
| bounds-checked access | no | yes, with v.at(i) |
| memory management | manual (if dynamic) | automatic |
Creating a vector
vector<int> v1; // empty vector
vector<int> v2(5); // 5 elements, each 0
vector<int> v3(4, 7); // 4 elements, each 7
vector<int> v4(v3); // copy of v3
int arr[] = {1, 2, 3};
vector<int> v5(arr, arr + 3); // from a range: 1 2 3Important member functions
| Function | Task |
|---|---|
push_back(x) | add x at the end |
pop_back() | remove the last element |
size() | number of elements |
capacity() | number of elements it can hold before it must reallocate |
empty() | true if there are no elements |
v[i] | element i (no bounds check) |
at(i) | element i, throws out_of_range if i is invalid |
front(), back() | first and last element |
begin(), end() | iterators |
insert(pos, x) | insert x before iterator pos |
erase(pos), erase(first, last) | remove one element or a range |
clear() | remove all elements |
resize(n) | change the size to n |
reserve(n) | make the capacity at least n |
swap(v2) | exchange contents with v2 |
Program: using a vector
#include <iostream>
#include <vector>
using namespace std;
void display(const vector<int>& v) {
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << "(size " << v.size() << ")" << endl;
}
int main() {
vector<int> v;
for (int i = 1; i <= 5; i++) {
v.push_back(i * 10); // 10 20 30 40 50
}
display(v);
v.insert(v.begin() + 2, 25); // insert before position 2
display(v);
v.erase(v.begin() + 4); // remove the element at position 4 (40)
display(v);
v.pop_back(); // remove the last element (50)
display(v);
cout << "front = " << v.front() << ", back = " << v.back() << endl;
v[0] = 5; // modify through []
display(v);
v.clear();
cout << "after clear, empty() = " << v.empty() << endl;
return 0;
}Output:
10 20 30 40 50 (size 5)
10 20 25 30 40 50 (size 6)
10 20 25 30 50 (size 5)
10 20 25 30 (size 4)
front = 10, back = 30
5 20 25 30 (size 4)
after clear, empty() = 1Size vs capacity
A vector usually reserves more memory than it needs so that push_back does not have to reallocate every time. size() is the number of elements in use; capacity() is how many fit in the memory already allocated. When size would exceed capacity, the vector allocates a bigger block (typically double), copies the elements across and frees the old block. That is why push_back is amortised O(1), and why iterators and pointers into a vector become invalid after a reallocation.
size and capacity of a vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.reserve(4); // ask for room for 4 elements in advance
for (int i = 1; i <= 4; i++) {
v.push_back(i);
cout << "size " << v.size() << ", capacity " << v.capacity() << endl;
}
v.resize(2); // shrink the size; capacity is unchanged
cout << "after resize(2): size " << v.size() << ", capacity " << v.capacity() << endl;
return 0;
}Output:
size 1, capacity 4
size 2, capacity 4
size 3, capacity 4
size 4, capacity 4
after resize(2): size 2, capacity 4Bounds checking with at()
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> marks(3, 80);
try {
cout << marks.at(1) << endl;
cout << marks.at(5) << endl; // invalid index: throws
} catch (out_of_range&) {
cout << "index out of range caught" << endl;
}
return 0;
}Output:
80
index out of range caughtv[5] would not be checked: it would silently read invalid memory (undefined behaviour).
A vector of objects
Vectors can hold class objects; the class needs a copy constructor and assignment (the compiler-generated ones are fine for simple classes).
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Student {
string name;
int marks;
public:
Student(string n, int m) {
name = n;
marks = m;
}
int getMarks() const {
return marks;
}
void show() const {
cout << name << ": " << marks << endl;
}
};
int main() {
vector<Student> cls;
cls.push_back(Student("Aditi", 88));
cls.push_back(Student("Rohan", 72));
cls.push_back(Student("Sana", 95));
int total = 0;
for (vector<Student>::iterator it = cls.begin(); it != cls.end(); ++it) {
it->show(); // -> works on iterators like on pointers
total = total + it->getMarks();
}
cout << "average = " << total / (int)cls.size() << endl;
return 0;
}Output:
Aditi: 88
Rohan: 72
Sana: 95
average = 85A 2-D vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
int rows = 3, cols = 4;
vector<vector<int> > grid(rows, vector<int>(cols, 0)); // note the space in "> >"
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
grid[i][j] = i * cols + j;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << grid[i][j] << "\t";
}
cout << endl;
}
return 0;
}Output:
0 1 2 3
4 5 6 7
8 9 10 11 In C++98 the space in vector< vector<int> > is required: without it, >> is read as the shift operator.
2. The list Container
A list is a doubly linked list (<list>). Each element is a separate node with links to the previous and next nodes, so:
- inserting or erasing anywhere is O(1) once you have an iterator to the position (no shifting of elements);
- there is no random access: no
[]and noat(); to reach the 100th element you must walk 99 links; - its iterators are bidirectional, so the general
sort()algorithm cannot be used;listhas its ownsort()member.
Extra members (besides those of vector): push_front, pop_front, sort, reverse, merge, unique, remove(value), splice.
#include <iostream>
#include <list>
using namespace std;
void show(const char* label, const list<int>& l) {
cout << label;
for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it) {
cout << " " << *it;
}
cout << endl;
}
int main() {
list<int> l;
l.push_back(30);
l.push_back(10);
l.push_front(50); // add at the front
l.push_back(20);
l.push_back(10);
show("list: ", l);
l.sort(); // list's own sort
show("sorted: ", l);
l.unique(); // remove consecutive duplicates
show("unique: ", l);
l.reverse();
show("reversed: ", l);
l.remove(30); // remove every 30
show("remove 30:", l);
list<int> other;
other.push_back(15);
other.push_back(25);
l.sort();
l.merge(other); // merge two sorted lists
show("merged: ", l);
cout << "other is now " << (other.empty() ? "empty" : "not empty") << endl;
return 0;
}Output:
list: 50 30 10 20 10
sorted: 10 10 20 30 50
unique: 10 20 30 50
reversed: 50 30 20 10
remove 30: 50 20 10
merged: 10 15 20 25 50
other is now empty3. The deque Container
A deque ("deck", double-ended queue, <deque>) supports fast insertion and deletion at both ends and also random access with []. Internally it is a set of fixed-size blocks, so it does not need one contiguous block like a vector.
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<int> d;
d.push_back(3);
d.push_back(4);
d.push_front(2); // fast at the front too
d.push_front(1);
for (size_t i = 0; i < d.size(); i++) {
cout << d[i] << " "; // random access
}
cout << endl;
d.pop_front();
d.pop_back();
cout << "after popping both ends: " << d.front() << " " << d.back() << endl;
return 0;
}Output:
1 2 3 4
after popping both ends: 2 34. Comparing the Sequence Containers
| Operation / feature | vector | deque | list |
|---|---|---|---|
| internal structure | one contiguous dynamic array | blocks of arrays | doubly linked nodes |
random access [] | yes, O(1) | yes, O(1) | no |
| insert/delete at end | O(1) amortised | O(1) | O(1) |
| insert/delete at front | O(n) | O(1) | O(1) |
| insert/delete in middle | O(n) | O(n) | O(1) at an iterator |
| iterator category | random access | random access | bidirectional |
push_front | no | yes | yes |
works with sort() algorithm | yes | yes | no (use l.sort()) |
| memory overhead | lowest | medium | highest (two links per node) |
| best for | most uses; indexing; adding at the end | queues; adding at both ends | frequent insertion/deletion in the middle |
Key points to remember
- Sequence containers:
vector,deque,list; elements are kept in insertion order. vector= dynamic, contiguous array:push_back,pop_back,[],at(),size(),capacity(),insert,erase.size()is elements in use;capacity()is room before reallocation; reallocation invalidates iterators.at(i)checks bounds and throwsout_of_range;[]does not.list= doubly linked list: fast insertion anywhere, no[], ownsort(),merge(),unique(),reverse().deque= fast at both ends with random access.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is a vector? Explain its member functions with a program. (10 Marks)
- Write: the definition, array vs vector table, the ways to create one, the member functions table, and the "using a vector" program with output.
- Q2. Differentiate between vector, list and deque. (10 Marks)
- Write: each container's structure, and the comparison table; add a short program for
list. - Q3. Write a program to store objects of a class in a vector and process them. (5 Marks)
- Write: the
Studentvector program. - Q4. Explain size and capacity of a vector. (5 Marks)
- Write: the definitions, reallocation, and the
reserveprogram. - Q5. What is the difference between
v[i]andv.at(i)? (2.5 Marks)