← 返回课程: Modern C++ from scratch

Week 4 practice and review: containers in action

视频即将上线

This week you met three tools: std::vector for sequences, std::array for fixed sizes and std::map or std::unordered_map for lookup by key. Today we combine them in a small but realistic program: a student grade book. You will see how to choose the right container for each need and how to pass data to functions without copying it. Before writing code it helps to think about the model: each student has a name and several grades, and we want to query by name. That calls for a map from name to a vector of grades.

A container inside another

Containers can be nested: std::map<std::string, std::vector<int>> stores a list of grades for each name. The expression grades["Ana"].push_back(8) is very convenient: [] creates Ana's entry with an empty vector if it did not exist, and push_back adds the grade. Here the side effect of [] is exactly what we want. To read without creating, on the other hand, use find and dereference the iterator: it->second is the vector. Remember to pass the vector to functions by const reference (const std::vector<int>&) so you do not copy all the grades every time you compute an average.

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

using GradeBook = std::map<std::string, std::vector<int>>;

double average(const std::vector<int>& values) {
    if (values.empty()) {
        return 0.0;   // avoids dividing by zero
    }
    int total{0};
    for (int v : values) {
        total += v;
    }
    return static_cast<double>(total) / values.size();
}

void addGrade(GradeBook& book, const std::string& student, int grade) {
    book[student].push_back(grade);   // creates the student if missing
}

int main() {
    GradeBook book;
    addGrade(book, "Ana", 8);
    addGrade(book, "Ana", 10);
    addGrade(book, "Luis", 6);
    addGrade(book, "Luis", 7);
    addGrade(book, "Luis", 5);

    for (const auto& [name, grades] : book) {
        std::cout << name << ": " << grades.size()
                  << " grades, average " << average(grades) << '\n';
    }
    // Ana: 2 grades, average 9
    // Luis: 3 grades, average 6
    return 0;
}

Finding the best student

To find the best average we traverse the map and keep track of the maximum seen so far, along with the name. A common mistake is to initialize the maximum to 0: if all grades were negative (or the map were empty) the result would be misleading. A clean solution is to check first that the map is not empty and start from the first element. Another detail: when storing the winning name use std::string (a copy) or a pointer to the element, but never a reference to something that is going to be destroyed. Here we store a copy of the name, which is simple and safe.

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

using GradeBook = std::map<std::string, std::vector<int>>;

double average(const std::vector<int>& values) {
    if (values.empty()) {
        return 0.0;
    }
    int total{0};
    for (int v : values) {
        total += v;
    }
    return static_cast<double>(total) / values.size();
}

// returns the name of the student with the best average, or "" if the book is empty
std::string bestStudent(const GradeBook& book) {
    if (book.empty()) {
        return "";
    }
    auto it = book.begin();
    std::string bestName = it->first;
    double bestAvg = average(it->second);
    for (++it; it != book.end(); ++it) {
        double avg = average(it->second);
        if (avg > bestAvg) {
            bestAvg = avg;
            bestName = it->first;
        }
    }
    return bestName;
}

int main() {
    GradeBook book{{"Ana", {8, 10}}, {"Luis", {6, 7, 5}}, {"Marta", {9, 9, 10}}};
    std::cout << "best: " << bestStudent(book) << '\n';   // best: Marta
    std::cout << "empty: [" << bestStudent(GradeBook{}) << "]\n";   // empty: []
    return 0;
}

Checklist before you finish

  • Do you pass large containers by const reference when you only read them?
  • Do you handle the empty container case before dividing or taking front()?
  • Do you use find or count when you only query a map?
  • Do you use size_t or static_cast when comparing or dividing with size()?
  • Do you avoid adding or removing elements inside a range-based for?

This list sums up the most frequent mistakes of the week. Calling front() or back() on an empty vector is undefined behavior, just like accessing with [] out of range; if in doubt, use at(), which throws a clear exception and makes debugging easier. Review your code with this list before calling an exercise done: almost all beginner failures with containers are here.

检验所学

第 1 / 6

Which container would you choose to store each student's grades, searching by name?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →