Arrays and std::vector
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Many values, one name
Programs rarely deal with one value. You have a list of prices, a set of names, rows from a file. C++ gives you several ways to hold a sequence of values. This lesson covers the three you need, and tells you which one to reach for.
Raw C arrays
The oldest form is the built-in array. Its size is fixed at compile time.
int scores[4]{90, 85, 70, 100};
std::cout << scores[0] << "\n"; // 90
It works, but it has sharp edges. It does not know its own size once passed to a function (it decays to a pointer). It does no bounds checking. Writing scores[10] compiles and silently reads or writes other memory. I recommend you recognise raw arrays when you read old code and avoid writing new ones.
std::array: fixed size, done properly
When the size is known at compile time, use std::array. It costs nothing extra over a raw array and knows its size.
#include <array>
#include <iostream>
int main() {
std::array<int, 4> scores{90, 85, 70, 100};
std::cout << "count: " << scores.size() << "\n";
std::cout << "second: " << scores.at(1) << "\n"; // bounds checked
for (int s : scores) std::cout << s << " ";
std::cout << "\n";
}
The member function at(i) throws std::out_of_range if i is too large. The square-bracket form scores[i] does not check. Use at while you are learning and when the index comes from outside.
std::vector: the default choice
Most of the time you do not know in advance how many items you will have. std::vector is a resizable array that manages its own memory. If you are unsure which container to use, use a vector. That advice is boring and nearly always right.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> prices{250, 120, 400};
prices.push_back(99); // add to the end
prices.push_back(310);
std::cout << "items: " << prices.size() << "\n";
std::cout << "first: " << prices.front() << ", last: " << prices.back() << "\n";
std::sort(prices.begin(), prices.end());
for (int p : prices) std::cout << p << " ";
std::cout << "\n"; // 99 120 250 310 400
prices.pop_back(); // remove the last element
prices.erase(prices.begin()); // remove the first element
std::cout << "left: " << prices.size() << "\n"; // 3
}
How a vector grows
A vector keeps its elements in one block of memory. When it runs out of room it allocates a bigger block, moves the elements across, and frees the old one. size() is how many elements it holds. capacity() is how many it can hold before the next reallocation. If you know roughly how many items are coming, call reserve(n) first and skip the repeated reallocations.
std::vector<double> readings;
readings.reserve(1000);
for (int i = 0; i < 1000; ++i) {
readings.push_back(i * 0.5);
}
A key consequence: when a vector reallocates, every pointer, reference and iterator into it becomes invalid. If you hold int* p = &v[0]; and then call push_back, p may be left dangling. This single fact explains many mysterious crashes.
Constructing vectors
Careful with brace and parenthesis forms, because they mean different things.
std::vector<int> a(5); // five elements, all 0
std::vector<int> b(5, 7); // five elements, all 7
std::vector<int> c{5, 7}; // two elements: 5 and 7
std::vector<std::string> d{"x", "y"};
Parentheses with a number mean "this many elements". Braces mean "these exact values". Mixing them up is a very common source of confusion.
Looping with indexes
When you need the index, use std::size_t or a signed type consistently. Comparing an int with size(), which is unsigned, produces a warning with -Wall -Wextra.
for (std::size_t i = 0; i < prices.size(); ++i) {
std::cout << i << ": " << prices[i] << "\n";
}
A trap here: for (std::size_t i = prices.size() - 1; i >= 0; --i) never ends, because an unsigned number is always at least zero. Counting down with unsigned types needs a different loop shape.
Two-dimensional data
A vector of vectors makes a simple grid.
std::vector<std::vector<int>> grid(3, std::vector<int>(4, 0)); // 3 rows, 4 columns
grid[1][2] = 9;
std::cout << grid[1][2] << "\n";
For big numeric grids, one flat vector with index row * columns + col is faster, because the data sits in one block. That is an optimisation for later.
The common mistake
Using operator[] out of range, and holding on to a reference after push_back. Both compile and may even appear to work. The other classic is erasing from a vector while looping over it with a range-for loop. Removing an element changes the container under the loop. Use the erase-remove idiom, or in C++20 std::erase_if(v, predicate), which does it in one safe call.
Try it yourself
- Read numbers from the user until they type 0, store them in a vector, then print the sum, the average and the largest.
- Use
std::erase_if(C++20) to remove all negative numbers from a vector. - Create a 5 by 5 grid and fill it with a multiplication table. Print it.
int scores[4]{90, 85, 70, 100};
std::cout << scores[0] << "\n"; // 90
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account