C/C++ Arena

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:

#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

Your task: top three without changing the input

The input is const, so you can't sort it in place. Two good approaches:

  1. 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.
  2. Keep the best three in the std::array as 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.

Previous: enum class Next: deque, the double-ended queue