C++ Arrays and Vectors
Arrays and vectors store many values of the same type under one name.
Arrays
An array has a fixed size that you choose when you create it:
Example
cpp
#include <iostream>
using namespace std;
int main() {
int marks[4] = {66, 89, 74, 92};
cout << marks[0] << "\n";
marks[1] = 90;
cout << marks[1] << "\n";
int total = 0;
for (int m : marks) {
total += m;
}
cout << "Total: " << total << "\n";
return 0;
}Output
66 90 Total: 322
Indexes start at 0, and C++ does not check them for you. Reading marks[4] in an array of 4 items gives garbage or a crash.
Vectors
A vector is like an array that can grow and shrink. It is the most used container in modern C++. Include <vector>:
Example
cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> cart = {"Milk", "Bread"};
cart.push_back("Eggs");
cart.push_back("Tea");
cout << "Items: " << cart.size() << "\n";
cout << "First: " << cart.front() << "\n";
cout << "Last: " << cart.back() << "\n";
cart.pop_back(); // remove Tea
for (const string& item : cart) {
cout << "- " << item << "\n";
}
return 0;
}Output
Items: 4 First: Milk Last: Tea - Milk - Bread - Eggs
Common Vector Functions
| Function | What it does |
|---|---|
v.push_back(x) | Adds x at the end |
v.pop_back() | Removes the last item |
v.size() | Number of items |
v[i] | Item at index i (no check) |
v.at(i) | Item at index i, with a safety check |
v.empty() | true if there are no items |
v.clear() | Removes all items |
Arrays vs Vectors
| Array | Vector | |
|---|---|---|
| Size | Fixed | Can change |
| Add items | Not possible | push_back |
| Knows its size | Not easily | size() |
| Best for | Small fixed lists | Almost everything else |
Sorting and Finding
The <algorithm> library works with vectors:
Example
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> prices = {499, 120, 850, 300};
sort(prices.begin(), prices.end());
for (int p : prices) {
cout << p << " ";
}
cout << "\n";
cout << "Max: " << *max_element(prices.begin(), prices.end()) << "\n";
return 0;
}Output
120 300 499 850 Max: 850
Two-Dimensional Data
Example
cpp
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << grid[0][2] << "\n"; // prints 3Exercise
Exercise
Which function adds an item to the end of a vector?
