Introducing std::map
Part of the Logic & Flow section of Coddy's C++ journey — lesson 23 of 56.
While vectors are excellent for storing collections of similar items, sometimes you need to associate one piece of data with another. This is where std::map becomes invaluable - it's a container that stores elements as key-value pairs.
Think of a map like a dictionary where each word (the key) has a corresponding definition (the value). In programming, you might use a map to store student names paired with their test scores, or product names paired with their prices. The key allows you to quickly look up its associated value.
To use std::map in your C++ programs, you need to include the <map> header at the top of your file:
#include <map>Maps are particularly useful when you need fast lookups based on a specific identifier, making them perfect for scenarios where you want to retrieve information using a meaningful key rather than a numeric index.
Cheat sheet
The std::map container stores elements as key-value pairs, like a dictionary where each key has a corresponding value.
To use std::map, include the header:
#include <map>Maps are useful for fast lookups based on a specific identifier, allowing you to retrieve information using a meaningful key rather than a numeric index.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items