Preferring std::array and std::vector over raw arrays buys you three things. The size travels with the data, the container knows how many elements it holds, and the interface is uniform enough that the algorithms written for one of them work on the other. The raw array is not wrong, it is just missing the parts that you would end up writing by hand anyway.
The previous lesson in this module covered "How Do Arrays Decay When Passed to Functions?", and the next lesson in this module is about "What Is the Difference Between C-Strings and std::string?".
std::array: fixed size, full interface
std::array wraps a raw array in a class. The storage is identical, so the performance is identical, but the type now carries its size and it offers the same interface as every other standard container.
#include <array>
#include <iostream>
int main() {
std::array<int, 4> ratings = {4, 5, 3, 5};
std::cout << "count: " << ratings.size() << '\n';
std::cout << "first: " << ratings.front() << '\n';
std::cout << "last: " << ratings.back() << '\n';
std::cout << "element 2: " << ratings[2] << '\n';
ratings[2] = 4;
std::cout << "after edit: ";
for (int r : ratings) {
std::cout << r << ' ';
}
std::cout << '\n';
return 0;
}The output shows the container behaving like an array with the methods attached.
count: 4
first: 4
last: 5
element 2: 3
after edit: 4 5 4 5The important gain is not the convenience of .front() and .back(). It is that std::array<int, 4> and std::array<int, 5> are different types, so passing the wrong one to a function is a compile error and not a run time bug.
std::vector: size decided at runtime
std::vector is a dynamic array. It owns its memory, it grows when you add to it, and it frees the memory when it goes out of scope.
#include <iostream>
#include <vector>
int main() {
std::vector<int> ratings;
for (int i = 0; i < 5; ++i) {
ratings.push_back(3 + (i % 3));
}
std::cout << "count: " << ratings.size() << '\n';
std::cout << "first: " << ratings.front() << '\n';
ratings[0] = 5;
ratings.at(0) = 5;
std::cout << "after edit: ";
for (int r : ratings) {
std::cout << r << ' ';
}
std::cout << '\n';
return 0;
}Notice the difference between ratings[0] and ratings.at(0). The subscript operator does not check the index. The .at() member does check it, and it throws an exception if the index is out of range.
The output shows the five ratings after the edit.
count: 5
first: 3
after edit: 5 4 5 3 4Comparing the two side by side
the property std::array std::vector
------------------ -------------------------------- --------------------------------
the size fixed at compile time changes at run time
the memory embedded in the object a separate allocation
the bounds checked by the compiler checked with .at()
the copy cost copies every element copies the elements too
but a vector can be moved
the interface .size() .begin() .end() etc. the same
And both of them satisfy the standard algorithms' requirements, so one function can handle either of them.
When to use which
Reach for std::array when the number of elements is fixed and known when you write the code. That means a small lookup table, a coordinate pair or a fixed-size buffer.
Reach for std::vector when the number of elements is only known at run time, or when it changes often.
And there is a third option that is worth knowing about, and it is std::span, which was added in C++20. It is a non-owning view of a contiguous sequence that knows its length, which is exactly what a raw array pointer plus a count wants to be.
Initialising a vector
A std::vector has several useful ways to be created, and they differ in what they do to the size and to the contents.
#include <iostream>
#include <vector>
int main() {
std::vector<int> empty; // no elements
std::vector<int> zeros(5); // five elements, all 0
std::vector<int> repeated(5, 2); // five elements, all 2
std::vector<int> from_list = {4, 5, 3}; // three elements from a list
std::vector<int> copied = from_list; // a copy of the three
std::cout << "empty: " << empty.size() << '\n';
std::cout << "zeros: " << zeros[0] << '\n';
std::cout << "repeated: " << repeated[4] << '\n';
std::cout << "copied: " << copied.size() << '\n';
return 0;
}The output confirms each of the constructions.
empty: 0
zeros: 0
repeated: 2
copied: 3Two of these deserve special mention. A vector that is constructed with a count, such as std::vector<int> zeros(5), creates five zero-valued elements. That is different from std::vector<int> zeros{5}, because with the braces the 5 is an element value, so you get one element that holds the number 5.
And a std::vector never shrinks when you assign it a smaller list. It keeps its capacity and it simply holds fewer elements.
Using one interface with both
The standard algorithms work on any container that provides the right iterators, so the same code handles an array and a vector.
#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <vector>
template <typename Shelf>
void report(const Shelf& shelf) {
std::cout << "count: " << shelf.size() << '\n';
std::cout << "total: " << std::accumulate(shelf.begin(), shelf.end(), 0) << '\n';
std::cout << "best: " << *std::max_element(shelf.begin(), shelf.end()) << '\n';
}
int main() {
std::array<int, 3> fixed_shelf = {4, 5, 3};
std::vector<int> growing_shelf = {4, 5, 3, 2, 5};
report(fixed_shelf);
report(growing_shelf);
return 0;
}One template handles both of the containers, and the output confirms it.
count: 3
total: 12
best: 5
count: 5
total: 19
best: 5Quick reference
std::arrayhas a compile-time size, no allocation, and the same memory layout as a raw array.std::vectorhas a run time size, it owns its memory, and it grows automatically.- Both of them give you
.size(),.begin(),.end(),.front()and.back(). .at()checks the index and throws, and the subscript operator does not check.- Both satisfy the standard algorithms' requirements, so one function can handle either of them.
- Use
std::arrayfor a fixed count, andstd::vectorfor a count that you only learn at run time.
Try it yourself: write the same average-rating program twice, once with a std::array of five elements and once with a std::vector that you fill at run time. Then write one template function that reports the count, the total and the best rating for either of them, and call it with both. Finally, replace the subscript with .at() and pass an index that is one too high so that you can see the exception.