C++ Vectors
std::vector is the most used container in C++. It is a dynamic array: elements are stored next to each other in memory (so access is very fast), but unlike a built-in array it can grow and shrink at runtime and it manages its own memory. When in doubt about which container to use, use a vector.
Creating a vector
Include <vector> and give the element type in angle brackets:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> cities = {"Paris", "Cairo", "Tokyo"};
vector<int> zeros(4); // 4 elements, all 0
vector<char> stars(3, '*'); // 3 copies of '*'
vector<double> empty; // no elements yet
cout << cities[1] << "\n";
cout << zeros.size() << " zeros, " << stars.size() << " stars, "
<< empty.size() << " in empty\n";
for (char c : stars) cout << c;
cout << "\n";
}Cairo
4 zeros, 3 stars, 0 in empty
***
Note:
vector<int> a(4);creates four zeros, whilevector<int> b{4};creates one element with value 4. Parentheses call a sizing constructor; braces list the elements.
Adding and removing elements
| Operation | Effect |
|---|---|
v.push_back(x) |
append x at the end |
v.emplace_back(args...) |
construct a new element in place at the end |
v.pop_back() |
remove the last element |
v.insert(v.begin() + i, x) |
insert x before position i |
v.erase(v.begin() + i) |
remove the element at position i |
v.clear() |
remove all elements |
#include <iostream>
#include <vector>
using namespace std;
void print(const vector<int>& v) {
for (int x : v) cout << x << " ";
cout << "(size " << v.size() << ")\n";
}
int main() {
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
print(v);
v.insert(v.begin() + 1, 15); // before index 1
print(v);
v.erase(v.begin()); // remove the first element
print(v);
v.pop_back();
print(v);
v.clear();
cout << boolalpha << "empty: " << v.empty() << "\n";
}10 20 30 (size 3)
10 15 20 30 (size 4)
15 20 30 (size 3)
15 20 (size 2)
empty: true
Adding or removing at the end is fast. Inserting or erasing at the front or middle has to shift every later element, so it is slow for big vectors.
Accessing elements
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> scores = {72, 88, 95, 61};
cout << "first: " << scores.front() << ", last: " << scores.back() << "\n";
scores[0] = 75; // fast, no bounds check
cout << "scores[0]: " << scores[0] << "\n";
try {
cout << scores.at(7) << "\n"; // bounds-checked
} catch (const out_of_range&) {
cout << "index 7 is out of range\n";
}
}first: 72, last: 61
scores[0]: 75
index 7 is out of range
Size and capacity
A vector reserves more memory than it currently needs (its capacity) so that most push_back calls do not have to reallocate. When the capacity runs out, the vector allocates a larger block and moves the elements across. If you know roughly how many elements are coming, call reserve to allocate once:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.reserve(100);
cout << "size " << v.size() << ", capacity at least 100: "
<< boolalpha << (v.capacity() >= 100) << "\n";
for (int i = 0; i < 100; i++) v.push_back(i * i);
cout << "size " << v.size() << ", last " << v.back() << "\n";
v.resize(5); // shrink to the first 5 elements
for (int x : v) cout << x << " ";
cout << "\n";
}size 0, capacity at least 100: true
size 100, last 9801
0 1 4 9 16
Warning: Reallocation moves elements to new memory, which invalidates pointers, references and iterators to them. Don't keep a pointer into a vector while you
push_backto it.
Vectors of objects and 2D vectors
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Task {
string title;
bool done;
};
int main() {
vector<Task> todo;
todo.push_back({"write report", true});
todo.emplace_back(Task{"call bank", false});
todo.push_back({"water plants", false});
for (const auto& t : todo) {
cout << (t.done ? "[x] " : "[ ] ") << t.title << "\n";
}
vector<vector<int>> grid(3, vector<int>(4, 0)); // 3 rows, 4 columns
grid[1][2] = 7;
for (const auto& row : grid) {
for (int cell : row) cout << cell;
cout << "\n";
}
}[x] write report
[ ] call bank
[ ] water plants
0000
0070
0000
Test yourself
What does vector<int> v(5); create?
- One element with value 5
- Five elements, all 0
- An empty vector with capacity 5
- A compile error
Which operation is fast on a large vector?
- Inserting at the front
- Erasing from the middle
- push_back at the end
- Inserting in the middle
What is the difference between v[i] and v.at(i)?
- None
- at() checks bounds and throws out_of_range
- [] checks bounds
- at() returns a copy