C++ Arrays and Vectors

Store many values in arrays and std::vector, access them by index and loop through them.

Lesson 8 of 44Beginner18 min read

Most programs work with lists of things: the scores of every player, the temperatures for each day, the items in a basket. Creating a separate variable for each value doesn't scale. Instead, C++ lets you keep many values of the same type together, in order, under one name.

There are two main tools. A classic array has a fixed size that you choose when you create it. A std::vector is a modern, flexible list that can grow and shrink while the program runs. In everyday C++, vectors are the usual choice, but you'll see arrays in older code and when the size never changes.

In this lesson you'll create both, read and change items by index, loop through them, and pass a vector to a function.

Arrays

C++
int scores[4] = {72, 88, 95, 60};
cout << scores[0];   // 72
scores[3] = 65;      // change the last item
  • The number in square brackets is the size, and it can't change later.
  • Items are numbered from 0, so a 4-item array has indexes 0 to 3.
  • C++ does not check that an index is valid. Reading scores[4] gives a random value or crashes, which makes these bugs hard to find.

std::vector

Include <vector> and say what type the vector holds in angle brackets:

C++
#include <vector>

vector<string> names = {"Ada", "Linus"};
names.push_back("Grace");      // add to the end
cout << names.size();          // 3
cout << names[1];              // Linus
cout << names.at(2);           // Grace
  • push_back() adds an item to the end; pop_back() removes the last one.
  • size() returns how many items there are.
  • .at(i) works like [i], but checks the index and reports an error if it's out of range.

Looping through values

A classic for loop gives you each index:

C++
for (size_t i = 0; i < names.size(); i++) {
    cout << i << ": " << names[i] << endl;
}

When you only need the values, the range-based for loop is shorter and safer, because there's no index to get wrong:

C++
for (const string& name : names) {
    cout << name << endl;
}

Use auto& instead of const auto& if you want to change the items inside the loop. size_t is an unsigned whole-number type used for sizes and indexes.

Passing vectors to functions

Pass a vector by const reference to read it without copying, or by plain reference to change it:

C++
double average(const vector<int>& nums) { ... }
void addPoints(vector<int>& nums, int bonus) { ... }

Passing vector<int> nums without & would copy every item, which is slow for large vectors and means your changes would be lost.

Inserting, removing and resizing vectors

push_back and pop_back only work at the end. To work anywhere else, give insert and erase a position, written as begin() plus an index:

C++
vector<int> v = {10, 20, 30};
v.insert(v.begin() + 1, 15);   // {10, 15, 20, 30}
v.erase(v.begin());            // {15, 20, 30}

Everything after the change has to shift along by one place, so inserting or erasing near the front of a large vector is slower than working at the end.

Member functionWhat it does
v.front(), v.back()First and last item
v.empty()true if there are no items
v.clear()Removes every item
v.resize(n)Grows or shrinks to exactly n items
vector<int> v(5, 0)Creates 5 items, all set to 0

Be careful with brackets when creating a vector: vector<int> a(5, 0) holds five zeros, but vector<int> b{5, 0} holds two numbers, 5 and 0. Round brackets give a size and a value; braces give the list of items.

If you like arrays but want the extra safety, std::array<int, 4> from <array> has a fixed size like a classic array, yet knows its own size(), supports .at() and can be copied and returned from functions like a vector.

C++ Arrays and Vectors Syntax

Arrays and vectors

Type arr[size] = {v1, v2, v3};
arr[index] = value;

#include <vector>
vector<Type> v = {v1, v2};
v.push_back(value);
v.size();
v.at(index);
for (const auto& item : v) { }

C++ Arrays and Vectors Summary

  • Arrays have a fixed size: int a[5] = {...};. Indexes run from 0 to size - 1.
  • vector<Type> is a resizable list from <vector>.
  • push_back, pop_back, size and at are the core vector functions.
  • Loop with an index, or use for (const auto& x : v) for each value.
  • Pass vectors to functions by reference to avoid copying.

C++ Arrays and Vectors Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Temperatures in an array

C++
#include <iostream>
using namespace std;

int main() {
    double temps[5] = {18.5, 21.0, 19.5, 23.0, 20.5};
    double total = 0;
    double highest = temps[0];

    for (int i = 0; i < 5; i++) {
        total += temps[i];
        if (temps[i] > highest) highest = temps[i];
    }

    cout << "Average: " << total / 5 << endl;
    cout << "Highest: " << highest << endl;
    return 0;
}
Output
Average: 20.5
Highest: 23
Line-by-line explanation
  1. Line 5An array of 5 doubles, set up with a list of values.
  2. Line 7Start the "highest so far" with the first value.
  3. Lines 9 to 12Visit every index from 0 to 4.
  4. Line 15cout prints 23.0 as 23.
Example 2

A growing to-do list

C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> todo = {"Buy milk"};
    todo.push_back("Walk dog");
    todo.push_back("Finish homework");

    cout << "Tasks: " << todo.size() << endl;
    for (size_t i = 0; i < todo.size(); i++) {
        cout << i + 1 << ". " << todo[i] << endl;
    }

    todo.pop_back();
    cout << "After pop_back: " << todo.size() << " tasks" << endl;
    return 0;
}
Output
Tasks: 3
1. Buy milk
2. Walk dog
3. Finish homework
After pop_back: 2 tasks
Line-by-line explanation
  1. Lines 7 to 9Start with one task and add two more.
  2. Lines 12 to 14Print each task with a human-friendly number (i + 1).
  3. Line 16Remove the last task.
Example 3

Vectors and functions

C++
#include <iostream>
#include <vector>
using namespace std;

double average(const vector<int>& nums) {
    int total = 0;
    for (int n : nums) total += n;
    return static_cast<double>(total) / nums.size();
}

void addBonus(vector<int>& nums, int bonus) {
    for (int& n : nums) n += bonus;
}

int main() {
    vector<int> scores = {60, 75, 82};
    cout << "Before: " << average(scores) << endl;
    addBonus(scores, 5);
    cout << "After: " << average(scores) << endl;
    return 0;
}
Output
Before: 72.3333
After: 77.3333
Line-by-line explanation
  1. Line 5const reference: read the vector without copying it.
  2. Line 11A plain reference, so the function can change the scores.
  3. Line 12int& n lets the loop change each item in place.
  4. Lines 17 to 19The average rises by exactly the bonus.

Common C++ Arrays and Vectors Mistakes

Going past the end

Don't
int a[3] = {1, 2, 3};
for (int i = 0; i <= 3; i++) cout << a[i];
Do
int a[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) cout << a[i];

a[3] doesn't exist. C++ won't stop you; it just reads whatever memory comes next.

Changing a copy in a range-based loop

Don't
for (int n : scores) n *= 2;   // scores unchanged
Do
for (int& n : scores) n *= 2;  // scores doubled

Using [] on an empty vector

Don't
vector<int> v;
v[0] = 5;
Do
vector<int> v;
v.push_back(5);

An empty vector has no item 0. Add items with push_back first.

C++ Arrays and Vectors in Real Projects

Vectors in real code

A game keeps its enemies in a vector<Enemy>, adding one when it spawns and removing it when it's defeated. Data tools read every line of a file into a vector<string>, and the standard library can sort a whole vector with a single call: sort(v.begin(), v.end());.

C++ Arrays and Vectors FAQ

How do I find the length of an array in C++?

Use std::size(arr), available since C++17, which gives the number of items in a classic array. Older code writes sizeof(arr) / sizeof(arr[0]). Neither works inside a function that received the array as a parameter, because the array has turned into a pointer by then; pass the size separately, or use a vector or std::array, which carry their size with them.

What is the difference between size and capacity in a vector?

size() is how many items the vector holds. capacity() is how many it can hold before it needs to allocate a bigger block of memory and move everything across. If you know roughly how many items you'll add, v.reserve(1000) sets the capacity up front without changing the size.

How do I check if a vector contains a value?

Use find from <algorithm>: if (find(v.begin(), v.end(), 42) != v.end()) is true when 42 is in the vector. find returns v.end() when nothing matches. If you check membership very often, a set or unordered_set does it faster.

How do I make a 2D vector in C++?

Make a vector of vectors: vector<vector<int>> grid(3, vector<int>(4, 0)); creates 3 rows of 4 zeros. Read and write items with two indexes, grid[row][col]. grid.size() gives the number of rows and grid[0].size() the number of columns.

Can I use a variable as the size of an array in C++?

Not in standard C++: a classic array's size must be a constant known when the program is compiled, such as const int N = 10;. g++ and clang accept int a[n] with a variable n as an extension, but Visual C++ rejects it and -pedantic makes g++ warn. When the size comes from user input or a calculation, use vector<int> a(n);.

C++ Arrays and Vectors Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code to add 42 to the end of the vector.

vector<int> v;
v.(42);
Predict the outputeasy

What does this print?

vector<char> letters = {'c', 'o', 'd', 'e'};
cout << letters[1] << letters.size();
Predict the outputmedium

What does this print?

vector<int> v = {1, 2, 3};
for (int& x : v) x = x * 10;
v.pop_back();
for (int x : v) cout << x << " ";
Multiple choicemedium

What does v.at(10) do if v has only 3 items?

Predict the outputmedium

What does this print?

vector<int> v = {3, 1, 4};
v.push_back(1);
cout << v.size() << " " << v.back() << endl;

C++ Arrays and Vectors Quiz

5 questions to check what you learned.

  1. What header do you need for std::vector?

    • <array>
    • <vector>
    • <list>
    • <iostream>
  2. What's the main difference between an array and a vector?

    • Arrays can hold strings; vectors can't
    • Vectors start counting at 1
    • A vector can change size; a classic array can't
    • Arrays are always faster to write
  3. Which loop visits every value in vector v without using an index?

    • for (int x : v)
    • for (v : int x)
    • foreach (int x in v)
    • for (x in v)
  4. Why pass a large vector as const vector<int>&?

    • It makes the vector constant everywhere
    • It's required for all vectors
    • It avoids copying the vector and prevents the function from changing it
    • It sorts the vector
  5. Why pass a vector to a function as const vector<int>&?

    • To make it bigger
    • To avoid copying it while promising not to change it
    • Vectors can't be passed by value
    • To sort it