Map

MamtaWardhani's avatar
Published May 10, 2022Updated Apr 13, 2025
Contribute to Docs

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 include int, 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 values
std::map<std::string, int> ages;
// Insert key-value pairs using different methods
// Using operator[]
ages["Alice"] = 30;
// Using insert with pair
ages.insert(std::pair<std::string, int>("Bob", 25));
// Using insert with initializer list
ages.insert({"Charlie", 35});
// Print the map contents
std::cout << "Map contents:" << std::endl;
for (const auto& pair : ages) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// Check the size of the map
std::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: 30
Bob: 25
Charlie: 35
Map 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 names
std::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 checking
std::cout << "US is for " << countries["US"] << std::endl;
// Access using at() - throws exception if key doesn't exist
try {
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 exists
auto 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 accessing
if (countries.count("FR") > 0) {
std::cout << "France exists in the map" << std::endl;
}
// Using operator[] will create an entry if it doesn't exist
std::cout << "ZZ is " << countries["ZZ"] << std::endl; // Creates entry with empty string
std::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 States
CA is for Canada
DE is for Exception: map::at
Found: UK is for United Kingdom
France exists in the map
ZZ is
Map size after accessing non-existent key: 6

This example demonstrates four different ways to access elements in a map:

  1. Using the subscript operator [] - simple but creates a new element if the key doesn’t exist.
  2. Using the .at() method - throws an exception if the key isn’t found.
  3. Using the .find() method - returns an iterator that you can check.
  4. 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:

Code
Output
Loading...

This example demonstrates various ways to add and modify elements in a map:

  1. Using the [] operator to add new elements or modify existing ones.
  2. Using the .insert() method which only adds elements if the key doesn’t already exist.
  3. Using the .emplace() method to construct elements in-place.
  4. 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.

All contributors

Contribute to Docs

Learn C++ on Codecademy