C++ Maps

C++ Maps: Key-Value Pairs

A Map (often called a dictionary or hash map in other languages) is an incredibly powerful data structure that stores data in Key-Value pairs.

Just like looking up a word in a real dictionary (the Key) to find its definition (the Value), a C++ map lets you associate specific keys with corresponding values.


1. Using a Map

To use a map, include the <map> library.

In a map:

Map Example

#include <iostream>
#include <map>
using namespace std;

int main() { // Create a map where the Key is a string, and Value is an integer map<string, int> userAges;

// Assigning values to keys using the [] operator userAges["Alice"] = 25; userAges["Bob"] = 30; userAges["Charlie"] = 22;

// Accessing a value using a key cout << "Bob's age is: " << userAges["Bob"] << "\n";

// Updating an existing value userAges["Alice"] = 26; cout << "Alice's updated age is: " << userAges["Alice"] << "\n";

return 0; }


2. Iterating Through a Map

To loop through a map, you need to understand that each item is a pair. You can access the key using .first and the value using .second.

Iteration Example

for (auto item : userAges) {
  cout << item.first << " is " << item.second << " years old.\n";
}

Exercise

?

In a C++ Map, which part of the pair must always be unique?