example3_use_with_custom_objects.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
#include <iostream>
#include <map>
#include <string>

class Student {
public:
    Student(const std::string& name, int age) : name(name), age(age) {}

    std::string getName() const { return name; }
    int getAge() const { return age; }

private:
    std::string name;
    int age;
};

// Custom comparator for Student objects
struct StudentComparator {
    bool operator()(const Student& a, const Student& b) const {
        return a.getName() < b.getName();
    }
};

int main() {
    std::map<Student, double, StudentComparator> studentGrades;

    studentGrades[Student("Alice", 20)] = 3.8;
    studentGrades[Student("Bob", 22)] = 3.5;
    studentGrades[Student("Charlie", 21)] = 3.9;

    for (const auto& pair : studentGrades) {
        std::cout << pair.first.getName() << " (Age: " << pair.first.getAge() 
                  << "): GPA = " << pair.second << std::endl;
    }

    return 0;
}
Back to std_map