Map
A map
is an associative container in C++ that stores key-value pairs in sorted order. Each key is unique and maps to a single value, enabling efficient data storage and retrieval based on keys. C++ maps use a self-balancing binary search tree, typically a red-black tree, to achieve logarithmic time complexity for common operations.
Maps support efficient lookup, insertion, and deletion based on unique keys. They suit use cases such as dictionaries, phone books, configuration settings, and any situation that requires associating values with unique identifiers. Unlike unordered maps, standard maps maintain their elements in sorted order by key, which is beneficial for range-based operations.
Syntax
To use maps in C++, include the <map>
header file:
#include <map>
// General syntax for creating a map
std::map<KeyType, ValueType> mapName;
Parameters:
KeyType
: The type of the keys in the map. Common key types includeint
,string
, or custom classes that have the less-than operator defined.ValueType
: The type of the mapped values. This can be any valid C++ type, including built-in types, STL containers, or user-defined classes.mapName
: The identifier for the map instance.
Return value:
Maps return various iterators and containers based on the operation performed. For example, .find()
returns an iterator to the element if found, or to .end()
if not found.
Example 1: Creating and Initializing a Map
This example demonstrates how to create and initialize a map that associates names with ages:
#include <iostream>#include <map>#include <string>int main() {// Create a map with string keys and integer valuesstd::map<std::string, int> ages;// Insert key-value pairs using different methods// Using operator[]ages["Alice"] = 30;// Using insert with pairages.insert(std::pair<std::string, int>("Bob", 25));// Using insert with initializer listages.insert({"Charlie", 35});// Print the map contentsstd::cout << "Map contents:" << std::endl;for (const auto& pair : ages) {std::cout << pair.first << ": " << pair.second << std::endl;}// Check the size of the mapstd::cout << "Map size: " << ages.size() << std::endl;return 0;}
This code creates a map that associates names
(strings) with ages
(integers). It demonstrates three different ways to insert elements into a map: using the subscript operator []
, using the .insert()
method with a pair
, and using .insert()
with an initializer list.
The output produced by this code will be:
Map contents:Alice: 30Bob: 25Charlie: 35Map size: 3
Notice that the elements are automatically sorted by key (alphabetically in this case).
Example 2: Accessing Elements from a Map
This example shows different ways to access elements in a map, including checking if a key exists.
#include <iostream>#include <map>#include <string>int main() {// Create a map of country codes to country namesstd::map<std::string, std::string> countries = {{"US", "United States"},{"CA", "Canada"},{"UK", "United Kingdom"},{"FR", "France"},{"JP", "Japan"}};// Access using operator[] - simple but no error checkingstd::cout << "US is for " << countries["US"] << std::endl;// Access using at() - throws exception if key doesn't existtry {std::cout << "CA is for " << countries.at("CA") << std::endl;std::cout << "DE is for " << countries.at("DE") << std::endl; // Will throw exception} catch (const std::out_of_range& e) {std::cout << "Exception: " << e.what() << std::endl;}// Access using find() - safer way to check if key existsauto it = countries.find("UK");if (it != countries.end()) {std::cout << "Found: " << it->first << " is for " << it->second << std::endl;} else {std::cout << "Key not found!" << std::endl;}// Check if a key exists before accessingif (countries.count("FR") > 0) {std::cout << "France exists in the map" << std::endl;}// Using operator[] will create an entry if it doesn't existstd::cout << "ZZ is " << countries["ZZ"] << std::endl; // Creates entry with empty stringstd::cout << "Map size after accessing non-existent key: " << countries.size() << std::endl;return 0;}
The output generated by this code will be:
US is for United StatesCA is for CanadaDE is for Exception: map::atFound: UK is for United KingdomFrance exists in the mapZZ isMap size after accessing non-existent key: 6
This example demonstrates four different ways to access elements in a map:
- Using the subscript operator
[]
- simple but creates a new element if the key doesn’t exist. - Using the
.at()
method - throws an exception if the key isn’t found. - Using the
.find()
method - returns an iterator that you can check. - Using the
.count()
method - checks if a key exists without modifying the map.
Note how using the []
operator with a non-existent key “ZZ” created a new entry with an empty string value, increasing the map’s size.
Codebyte Example: Adding and Modifying Elements in a Map
This example shows how to add new elements and modify existing ones in a map:
This example demonstrates various ways to add and modify elements in a map:
- Using the
[]
operator to add new elements or modify existing ones. - Using the
.insert()
method which only adds elements if the key doesn’t already exist. - Using the
.emplace()
method to construct elements in-place. - Using the
.at()
method to modify existing elements with bounds checking.
Note that the elements are always sorted by key (alphabetically in this case).
Frequently Asked Questions
1. What is the difference between a map and an unordered map in C++?
A map keeps its elements sorted by key and is typically implemented as a balanced binary search tree, providing logarithmic time complexity for operations. An unordered map uses a hash table implementation, offering constant time complexity on average but without ordering guarantees.
2. Can I use custom objects as keys in a map?
Yes, but you must provide a comparison operator (`operator
Map
- .clear()
- Removes all elements from a map.
- .count()
- Checks whether a specified key exists in the map and returns the number of occurrences
- .emplace()
- Constructs and inserts an element into a map if the key does not already exist.
- .empty()
- Checks if a given map is empty.
- .end()
- Returns an iterator referring to the past-the-end element in a map container.
- .erase()
- Removes an element by key from a map.
- .find()
- Searches for an element with a particular key in a map.
- .insert()
- Inserts a key-value pair into a map.
- .size()
- Determines the number of elements in a map.
- .swap()
- Exchanges the content of two maps.
- .upper_bound()
- Returns an iterator pointing to the first element in the map container whose key is considered to go after the specified key.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours