Beginner · References, pointers, arrays and strings · topic 11 of 42 · 30 min
Arrays, std::array and a first look at std::vector
Explanation
Why arrays?
Storing the marks of 60 students in 60 separate variables is impossible to manage. An array is one variable that holds many values of the same type in a row, next to each other in memory. Each value is an element, and you reach it by its index: its position, starting from 0.
C-style arrays
int marks[5] = {78, 91, 64, 85, 70};
std::cout << marks[0] << '\n'; // 78, the first element
marks[4] = 72; // change the last one (index 4, not 5)
int scores[3] = {}; // all three are 0
const int N = 4;
double prices[N] = {10.5, 20.0}; // the rest become 0.0C-style arrays also forget their size when passed to a function: they "decay" into a pointer to the first element. That is why C functions take the size as a separate parameter.
std::array: a fixed array that knows its size
#include <array>
std::array<int, 5> marks = {78, 91, 64, 85, 70};
std::cout << marks.size() << '\n'; // 5
std::cout << marks.at(2) << '\n'; // 64, with bounds checking
// marks.at(9) throws std::out_of_range instead of corrupting memorystd::vector: an array that grows
#include <vector>
std::vector<int> orders; // empty
orders.push_back(450); // add at the end
orders.push_back(1200);
orders.push_back(99);
std::cout << orders.size() << '\n'; // 3
std::cout << orders[1] << '\n'; // 1200
std::vector<int> zeros(10, 0); // 10 elements, all 0
for (int o : orders) std::cout << o << ' ';2D arrays: rows and columns
int seats[3][4] = {}; // 3 rows, 4 columns, all 0
seats[1][2] = 1; // book row 1, column 2
std::vector<std::vector<char>> grid(3, std::vector<char>(4, '.'));
grid[0][3] = '#';
for (const auto& row : grid) {
for (char c : row) std::cout << c;
std::cout << '\n';
}Which one should I use?
| Need | Use |
|---|---|
| A list whose size changes or is read from input | std::vector<T> |
| A small list whose size is fixed at compile time | std::array<T, N> |
| Talking to C code or very old code | C-style array |
Common mistakes
- Using <= size in a loop: for (int i = 0; i <= 5; ++i) on a 5-element array goes one past the end.
- Using sizeof(arr) inside a function to get the length: it gives the size of a pointer there.
- Indexing an empty vector: v[0] on an empty vector is undefined behaviour. Check v.empty() first, or use v.at(0), which throws an exception.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Arrays, std::array and a first look at std::vector · 1/6
An array keeps many values of one type in a row, reached by an index that starts at zero.
Prefer a video by a teacher? Find free videos on “c++ arrays std::array std::vector tutorial beginners” on YouTube ↗
In real life: Cinema seat booking
A multiplex app shows a grid of seats: rows A to J and numbered columns. The program stores the hall as a 2D grid of characters, marks booked seats, and counts free seats in a row before you pay.
#include <iostream>
#include <vector>
int main() {
int rows = 3, cols = 6;
std::vector<std::vector<char>> hall(rows, std::vector<char>(cols, 'O'));
hall[1][2] = 'X';
hall[1][3] = 'X';
int freeInRowB = 0;
for (char seat : hall[1]) {
if (seat == 'O') ++freeInRowB;
}
std::cout << "Free seats in row B: " << freeInRowB << '\n'; // 4
}Practice (0/4 done)
int a[4] = {5, 10, 15, 20}; What is a[3]?
What does this print? std::vector<int> v = {3, 1, 4}; v.push_back(1); v.push_back(5); std::cout << v.size() << " " << v[3];
int m[3] = {1, 2, 3}; std::cout << m[3]; What happens?
Read n, then n daily temperatures into a std::vector<int>. Print the average, the highest and the lowest temperature, and how many days were above the average.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Text: C strings and std::stringReferences, pointers, arrays and strings · same module
- References: another name for a variableReferences, pointers, arrays and strings · same module
- std::vector in depthThe Standard Template Library (STL)
- Arrays: one name, many valuesC# and .NET · Arrays, strings and null
- Dynamic strings and 2D arraysC Programming (from zero to systems) · Dynamic memory
- 2D arrays and classic array algorithmsC Programming (from zero to systems) · Functions and arrays
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the index of the LAST element of an array of size 10?
Answer: 9
Indexes run from 0 to size - 1.
What is the main advantage of std::vector over a C-style array?
Answer: Its size can change at run time and it knows its size
vector grows with push_back and reports size(); it also manages its own memory.
What does v.at(10) do on a vector of size 3?
Answer: Throws std::out_of_range
.at() checks the index and throws an exception; [] does not check.
int a[5] = {1, 2}; What are a[2], a[3] and a[4]?
Answer: 0, 0, 0
When an initialiser list is shorter than the array, the remaining elements are zero-initialised.
Why do C functions that take an array also take its size?
Answer: Because a C array passed to a function decays into a pointer and loses its size
Inside the function the array is just a pointer to the first element.
What does std::remove(v.begin(), v.end(), 0) do on its own?Related
Answer: Moves non-zero elements to the front and returns the new logical end; the size is unchanged
You must call erase with the returned iterator to actually shrink the vector.
From std::vector in depth
What is the index of the last item in an array of length 8?Related
std::string a = "apple", b = "Apple"; Is a == b?Related
Answer: No, comparison is case sensitive
Characters are compared exactly; 'a' and 'A' are different.
How many frees does an array of 5 row pointers (each row malloc'd) need?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “References, pointers, arrays and strings” before its exam: Text: C strings and std::string.
- Module 3 exam: References, pointers, arrays and strings · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Classes, constructors and RAII. 42 topics left in the course before the final exam.