example4_nested_maps_complex_data_structures.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <map>
#include <string>
#include <vector>

// Function to print the course roster
void printCourseRoster(const std::map<std::string, std::map<std::string, std::vector<int>>>& university) {
    for (const auto& dept : university) {
        std::cout << "Department: " << dept.first << std::endl;
        for (const auto& course : dept.second) {
            std::cout << "  Course: " << course.first << ", Students: ";
            for (int studentId : course.second) {
                std::cout << studentId << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
}

int main() {
    // Map structure: Department -> (Course -> List of Student IDs)
    std::map<std::string, std::map<std::string, std::vector<int>>> university;

    // Adding data
    university["Computer Science"]["Programming 101"] = {1001, 1002, 1003};
    university["Computer Science"]["Data Structures"] = {1002, 1004, 1005};
    university["Mathematics"]["Calculus I"] = {1001, 1005, 1006};
    university["Mathematics"]["Linear Algebra"] = {1003, 1004, 1006};

    // Print the course roster
    printCourseRoster(university);

    // Adding a new student to a course
    university["Computer Science"]["Programming 101"].push_back(1007);

    // Checking if a department exists
    std::string deptToCheck = "Physics";
    if (university.find(deptToCheck) == university.end()) {
        std::cout << deptToCheck << " department does not exist." << std::endl;
    }

    return 0;
}
Back to std_map