Step 2 of 7
std::array
std::array<T, N> (from <array>) is a fixed-size array whose size N is part of its type. It's exactly as fast as a C array, with none of the surprises. Compared with a C array it:
- knows its size (
.size()), - doesn't decay to a pointer, so functions receive the whole thing,
- can be copied, compared with
==and returned from functions, - has bounds-checked access with
.at(i), which reports an error instead of silently reading garbage.
#include <algorithm>
#include <array>
#include <iostream>
std::array<int, 3> sorted_copy(std::array<int, 3> a) { // taken by value: a real copy
std::sort(a.begin(), a.end());
return a; // arrays can be returned
}
int main() {
std::array<int, 3> rgb = {200, 30, 90};
std::array<int, 3> s = sorted_copy(rgb);
std::cout << rgb[0] << " " << s[0] << " " << s.size() << "\n";
std::cout << (s == std::array<int, 3>{30, 90, 200}) << "\n";
std::array<double, 4> zeros{}; // {} zero-fills
zeros.back() = 1.5;
for (double z : zeros) std::cout << z << " ";
std::cout << "\n";
}
200 30 3
1
0 0 0 1.5
Reading the example
sorted_copygets its own copy, so sorting it leavesrgbuntouched. A C array parameter would have been a pointer to the caller's data.==compares element by element.std::array<double, 4> zeros{};fills with zeros. Without the{}, local numbers start as garbage, just like a C array.
Your task: top three without changing the input
The input is const, so you can't sort it in place. Two good approaches:
- Copy it into a local
std::vector, sort that copy descending (std::greater<int>()from the algorithms module), and take the first three that exist. - Keep the best three in the
std::arrayas you scan, shifting values down when a new one beats them.
Either way, start the result as {0, 0, 0} so missing places are already 0.
Your turn: write std::array<int, 3> podium(const std::vector<int>& scores) returning the three highest scores, highest first. Missing places are 0. Don't modify the input.