Here’s a quick example of using a C++ map:
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> grades;
grades["John"] = 85;
grades["Jane"] = 92;
grades["Jim"] = 78;
std::cout << "John's grade: " << grades["John"] << std::endl;
std::cout << "Jane's grade: " << grades["Jane"] << std::endl;
std::cout << "Jim's grade: " << grades["Jim"] << std::endl;
return 0;
}
In this example, we use a std::map to store the grades of three students (John, Jane, and Jim). Each student’s name is used as a key to look up their corresponding grade. The code uses the [] operator to insert new grades into the map and to look up existing grades.
When we run this program, it outputs the following:
John’s grade: 85
Jane’s grade: 92
Jim’s grade: 78
This demonstrates how a std::map can be used to store key-value pairs and look up values based on keys. It’s a powerful and flexible container that can be used in many applications.