Tutorials / C++: From Basics to Modern C++ / Arrays and std::vector

Arrays and std::vector

15 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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

  1. Read numbers from the user until they type 0, store them in a vector, then print the sum, the average and the largest.
  2. Use std::erase_if (C++20) to remove all negative numbers from a vector.
  3. Create a 5 by 5 grid and fill it with a multiplication table. Print it.
cpp
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