Start learning free

LESSON 201 OF 667 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in C++: Grades per Subject with a map

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

map<string, int> grades;
grades["Math"] = 92;
grades["English"] = 78;
grades["Science"] = 85;
grades["History"] = 67;

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a map<string, int> - it stores keys in sorted order.

map<string, int> grades;
grades["Math"] = 92;
grades["English"] = 78;
grades["Science"] = 85;
grades["History"] = 67;

for (auto& kv : grades) {
    const string& subject = kv.first;
    int score = kv.second;
    string grade;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    cout << subject << ": " << grade << endl;
}

STEP 1 OF 10
    Ctrl + Enter to check

    C++ · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in C++, explained

    Problem overview

    Version 5 keeps the same letter-grade scale but changes where the data lives. Instead of two parallel vectors, the scores are in a map<string, int> named grades, which links each subject to a score: Math 92, English 78, Science 85 and History 67. The program prints each subject with its letter grade, in alphabetical order:

    English: C
    History: D
    Math: A
    Science: B
    

    Notice that the subjects were added in a different order (Math first), yet the output starts with English. A map takes care of the order.

    Approach: loop over the key-value pairs

    A std::map keeps its keys sorted. Strings compare alphabetically, so going through the map from start to end visits the subjects from A to Z, without any sorting code of your own. (This is a property of map. An unordered_map makes no such promise.)

    A range-based for over a map gives you one element per pass. Each element is a pair: its first field is the key (the subject) and its second field is the value (the score). With auto& kv, the compiler works out the pair type, and the & means the loop refers to the stored pair instead of making a copy.

    After that, the body is the same grading ladder as in the previous version.

    Why a map instead of two vectors

    In the previous version the name and the score were linked by position, so you had to keep two vectors in step. A map stores the link itself: each subject is stored together with its own score, so there is no index to keep aligned, and adding or removing a subject changes only one place.

    The loop also changes shape. An index loop asks "what is at position i?" for each position. The range-based loop asks for every entry in turn and hands you the entry directly. You don't write a counter, a condition or a step, so there is nothing to get off by one.

    A map also looks things up by key. Writing grades["Math"] gives Math's score, without searching through a list. This lesson doesn't need a lookup, but it is the main reason to choose a map.

    Step by step

    1. Write for (auto& kv : grades). Close its brace right away and work inside it.
    2. Name the key: const string& subject = kv.first;. A const reference reads the subject without copying it and without being able to change it. Keys in a map are constant anyway.
    3. Name the value: int score = kv.second;.
    4. Declare an empty string grade; for the ladder to fill.
    5. Test for A: score >= 90 gives "A".
    6. Add the else if for 80 that gives "B".
    7. Add the else if for 70 that gives "C".
    8. Add the else if for 60 that gives "D".
    9. Close the ladder with else for "F".
    10. Print inside the loop: the subject, a colon and a space, then the grade. That gives one line per subject.

    The solution in C++

    map<string, int> grades;
    grades["Math"] = 92;
    grades["English"] = 78;
    grades["Science"] = 85;
    grades["History"] = 67;
    
    for (auto& kv : grades) {
        const string& subject = kv.first;
        int score = kv.second;
        string grade;
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        cout << subject << ": " << grade << endl;
    }
    

    Naming subject and score instead of using kv.first and kv.second everywhere makes the ladder and the print line easier to read. The loop never needs the index of an entry: a map has no positions, only keys.

    If you wrote auto kv without the &, the program would print the same four lines, but each pass would copy the pair, including the subject string. For a small map that cost is invisible; for a large map of long strings the reference is the better habit.

    Reading a map: the [] trap

    The starter code fills the map with grades["Math"] = 92;. The [] operator on a map inserts a default value when the key isn't there. On the starter map, which has 4 entries, reading grades["Art"] returns 0 and leaves the map with 5 entries, and a later loop would print Art: F. To read a key without adding it, use grades.find("Art") (compared against grades.end()) or grades.count("Art"). This lesson avoids the issue because the loop gives you keys and values that already exist.

    Edge cases and common mistakes

    • Expecting insertion order. The map orders by key, so English comes before Math although Math was added first. If you needed the original order, you would use a vector of pairs instead.
    • Treating kv as a number. kv is a pair. Use kv.first and kv.second.
    • Keys are case-sensitive. Uppercase letters sort before lowercase ones, so "english" would come after "Science" in the loop.
    • Printing outside the loop. The grade belongs to one subject, so the print stays in the loop body.
    • Boundaries. 90 is an A and 60 is a D, so use >=.

    Testing

    Run the starter data and compare the four lines with the output above. Then change History to 60. It should now print History: D too, and the lines should stay in the same order.

    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free