C++ Arrays
An array holds a fixed number of values of the same type, reached by index from 0. C++ has the built-in arrays inherited from C and the safer std::array from the array header. When the size must change while the program runs, use std::vector (see Vectors).
Built-in arrays
#include <iostream>
int main() {
int marks[5] = {78, 85, 62, 90, 74};
int total = 0, highest = marks[0];
for (int m : marks) {
total += m;
if (m > highest) highest = m;
}
std::cout << "Total: " << total << ", highest: " << highest << "\n";
std::cout << "Third mark: " << marks[2] << "\n";
return 0;
}Total: 389, highest: 90 Third mark: 62
Indexes run from 0 to size − 1. C++ does not check them: marks[5] reads memory that is not part of the array. Safe mode in the editor stops the program at such an index.
std::array
std::array has the same speed as a built-in array, but it knows its size, can be copied and compared, and offers at(i), which checks the index:
#include <array>
#include <iostream>
int main() {
std::array<int, 4> a = {3, 1, 4, 1};
std::cout << "size: " << a.size() << "\n";
std::array<int, 4> b = a; // a real copy
b[0] = 9;
std::cout << a[0] << " " << b[0] << "\n";
std::cout << "front " << a.front() << ", back " << a.back() << "\n";
return 0;
}size: 4 3 9 front 3, back 1
The size is part of the type (std::array<int, 4>) and must be a constant.
Two dimensions
#include <iostream>
int main() {
int table[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
std::cout << table[r][c] << " ";
}
std::cout << "\n";
}
std::cout << "table[1][2] = " << table[1][2] << "\n";
return 0;
}1 2 3 4 5 6 table[1][2] = 6
Arrays or vectors?
Built-in arrays turn into a pointer when passed to a function and forget their size, which causes many bugs. Prefer std::array for a fixed size and std::vector when the size is known only while the program runs. Most C++ code uses std::vector by default.
Passing arrays to functions
A std::array is passed like any object: by const& to read it, by & to change it, and the function knows its size. A built-in array passed to a function turns into a pointer to its first element and forgets its size, so the size must be passed separately, which is a common source of bugs.
Practice exercises
- Read 5 numbers into a
std::arrayand print them in reverse order. - Count how many elements are above the average.
- Find the smallest value and its position in one loop.
- Store a 3 by 3 table and print the sum of each row and each column.