← Retour au cours: Modern C++ from scratch

std::vector, std::array and the range-based for

Vidéo bientôt disponible

Almost every program needs to store many values of the same type: grades, prices, names. The standard library (STL) offers ready-made containers for this, and the most important is std::vector, a sequence that grows and shrinks as needed and manages its own memory. Next to it we see std::array, of fixed size, and the range-based for loop, the modern way to traverse them. With these tools you need neither C-style arrays nor manual memory.

std::vector

It is included with <vector> and declared by giving the element type in angle brackets: std::vector<int> nums;. You can initialize it with values: std::vector<int> nums{4, 8, 15}; (thanks to CTAD, since C++17 you can even omit the type: std::vector v{1, 2, 3};). push_back appends at the end, pop_back removes the last one, size() gives the count, empty() tells whether it is empty, clear() empties it, and front() and back() return the first and last. You access by index with v[i] (unchecked) or v.at(i) (checked). Internally the elements are contiguous in memory, which is why it is fast and usually the first choice.

cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> scores{70, 85, 90};
    scores.push_back(60);
    scores.push_back(100);

    std::cout << "count = " << scores.size() << '\n';
    std::cout << "first = " << scores.front() << ", last = " << scores.back() << '\n';

    // classic loop with index
    for (std::size_t i = 0; i < scores.size(); ++i) {
        std::cout << scores[i] << ' ';
    }
    std::cout << '\n';

    // range-based for: simpler and safer
    int total{0};
    for (int s : scores) {
        total += s;
    }
    std::cout << "average = " << static_cast<double>(total) / scores.size() << '\n';

    std::vector<std::string> names{"Ana", "Luis"};
    names.push_back("Marta");
    for (const std::string& n : names) {   // const& avoids copies
        std::cout << n << '\n';
    }
    return 0;
}

Range-based for: copy, reference and const

In for (T x : v) each x is a copy of the element, fine for integers but costly for strings. Use for (const T& x : v) to read without copying, and for (T& x : v) when you want to modify the container's elements. With auto it gets shorter: for (const auto& x : v). A very frequent mistake is modifying a container while you traverse it: adding or removing elements inside the loop can invalidate iterators and cause undefined behavior. If you need to add while traversing, do it afterwards or use indices very carefully.

std::array: fixed size

std::array<T, N>, in <array>, is an array whose size is known at compile time. It uses no dynamic memory, knows its size with size() and does not decay to a pointer when passed to a function, unlike C arrays. Use it when the count is fixed and small, like the days of the week or x, y, z coordinates. If the size may vary, use vector.

cpp
#include <array>
#include <iostream>
#include <vector>

double sum(const std::vector<double>& values) {
    double total{0.0};
    for (double v : values) {
        total += v;
    }
    return total;
}

void doubleAll(std::vector<int>& values) {
    for (int& v : values) {   // reference: modifies the original
        v *= 2;
    }
}

int main() {
    std::array<int, 3> point{3, 4, 5};
    std::cout << "point size = " << point.size() << ", y = " << point[1] << '\n';

    std::vector<double> prices{9.5, 20.0, 4.5};
    std::cout << "sum = " << sum(prices) << '\n';

    std::vector<int> nums{1, 2, 3};
    doubleAll(nums);
    for (int n : nums) {
        std::cout << n << ' ';   // 2 4 6
    }
    std::cout << '\n';
    return 0;
}

A surprising detail about types: size() returns an unsigned value (std::size_t). If you write for (int i = 0; i < v.size(); ++i) you will get a warning comparing signed and unsigned, and a loop like for (std::size_t i = v.size() - 1; i >= 0; --i) never ends, because an unsigned value is never negative. Use std::size_t for indices, or better still a range-based for when you do not need the index.

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →