---
description: What is std::map? In C++, a MAP is an associative container storing items in a mapped form. Each item in the map is composed of key-value and a mapped value. Two mapped values cannot share the same k
title: Map in C++ Standard Template Library (STL)
image: https://www.guru99.com/images/map-in-cpp-stl.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Map in C++ is an associative container from the Standard Template Library that stores elements as sorted key-value pairs, where each unique key maps to one value and enables fast lookup, insertion, and ordered traversal.

* 🗺️ **Associative container:** A C++ map stores items as key-value pairs with unique, automatically sorted keys.
* 🧩 **Header and syntax:** Include the map header, then declare std::map<key\_type, value\_type> name to store typed pairs.
* 🛠️ **Built-in functions:** begin(), size(), empty(), insert(), find(), erase(), and clear() manage map contents.
* 🔄 **Iteration:** A bidirectional iterator walks map elements in sorted key order for reading or deletion.
* 🔑 **Unique keys:** Two elements cannot share a key, which makes a map ideal as an associative array.
* 🤖 **AI assistance:** GitHub Copilot and similar AI assistants scaffold map declarations and loops from a short comment.

[ Read More ](javascript:void%280%29;) 

![Map in C++ STL](https://www.guru99.com/images/map-in-cpp-stl.png)

## What is Map in C++?

In C++, a MAP is an associative container storing items in a mapped form. Each item in the map is composed of a key value and a mapped value. Two mapped values cannot share the same key values.

The key values are useful for sorting and identifying elements uniquely, while the mapped values store the content associated with each key. The two may differ in type, but the member type combines them into a pair that holds both.

Before writing any code, it helps to know why a map is often the right container to reach for.

## Why use std::map?

Here are reasons for using a map:

* std::map stores unique keys only, in sorted order based on the chosen sorting criteria.
* It is easy and fast to search for elements using the key.
* Only one element is attached to each key.
* std::map can be used as an associative array.
* std::map is implementable using balanced binary trees.

To put these benefits to use, start with the declaration syntax.

## Syntax

To declare std::map, use this syntax:

std::map<key_datatype, value_datatype>map_name; 

* The **key\_datatype** denotes the datatype of the map keys.
* The **value\_datatype** denotes the datatype of the values corresponding to the map keys.
* The **map\_name** is the name of the map.

For example:

map<string, int> my_map; 

We declared a map named my\_map. The map will have a string as the key datatype and an integer as the values datatype.

## Member types

The member functions can use the following member types as either parameters or return type:

* **key\_type:** Key (the first parameter in the template)
* **mapped\_type:** T (the second parameter in the template)
* **key\_compare:** Compare (the third parameter in the template)
* **allocator\_type:** Alloc (the fourth parameter in the template)
* **value\_type:** pair<const key\_type,mapped\_type>
* **value\_compare:** Nested function class for comparing elements
* **reference:** allocator\_type::reference
* **const\_reference:** allocator\_type::const\_reference
* **[pointer](https://www.guru99.com/cpp-pointers.html):** allocator\_type::pointer
* **const\_pointer:** allocator\_type::const\_pointer
* **iterator:** a bi-directional iterator to the value\_type
* **const\_iterator:** a bi-directional iterator to the const value\_type
* **reverse\_iterator:** a reverse iterator
* **const\_reverse\_iterator:** a constant reverse iterator
* **difference\_type:** ptrdiff\_t
* **size\_type:** size\_t

## Built-in Functions of std::map

std::map comes with inbuilt functions. Some of these include:

* **begin()** – This function returns the iterator to the first item of the map.
* **size()** – This function returns the number of items in a map.
* **empty()** – This function returns a Boolean value denoting whether a map is empty.
* **insert(pair(key, value))** – This function inserts a new key-value pair into a map.
* **find(val)** – This function gives the iterator to the val element if it is found. Otherwise, it returns m.end().
* **erase(iterator position)** – This function deletes the item at the position pointed to by the iterator.
* **erase(const g)** – This function deletes the key-value g from a map.
* **clear()** – This function deletes all items from a map.

With the functions defined, the following examples put them into action, starting with iteration.

## Iterating over Map Elements

You can iterate over the map elements. We simply need to create an iterator and use it for this. For example:

### Example 1

#include <iostream>
#include <string>
#include <map> 

using namespace std;
int main() {

	map<int, string> Students;

	Students.insert(std::pair<int, string>(200, "Alice"));

	Students.insert(std::pair<int, string>(201, "John"));

	cout << "Map size is: " << Students.size() << endl;

	cout << endl << "Default map Order is: " << endl;

	for (map<int, string>::iterator it = Students.begin(); it != Students.end(); ++it) {

		cout << (*it).first << ": " << (*it).second << endl;
	}
}

Output:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan1.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan2.png)

Code Explanation:

1. Include the iostream header file into our code to use its functions.
2. Include the string header file into our code to use its functions.
3. Include the map header file into our code to use its functions.
4. Include the std namespace into our code to use its classes without calling it.
5. Call the main() function. The { marks the beginning of the body of the function.
6. Create a map named Students where the keys will be integers, and the values will be strings.
7. Insert values into the map Students. A key of 200 and a value of Alice will be inserted into the map.
8. Insert values into the map Students. A key of 201 and a value of John will be inserted into the map.
9. Use the size() function to get the size of the map named Students. This should return a 2.
10. Print some text on the console.
11. Use a for loop to create an iterator named it to iterate over the elements of the map named Students.
12. Print the values of the map Students on the console.
13. End of the body of the for loop.
14. End of the body of the main() function.

### RELATED ARTICLES

* [Arrays in C++: Declare, Initialize & Pointers (Examples) ](https://www.guru99.com/arrays-in-cpp-functions.html "Arrays in C++: Declare, Initialize & Pointers (Examples)")
* [std::list in C++ with Example ](https://www.guru99.com/cpp-list.html "std::list in C++ with Example")
* [Vector in C++ Standard Template Library (STL) with Example ](https://www.guru99.com/cpp-vector-stl.html "Vector in C++ Standard Template Library (STL) with Example")
* [C++ Functions with Program Examples ](https://www.guru99.com/cpp-functions.html "C++ Functions with Program Examples")

## Inserting data in std::map

You can enter items into std::map using the insert() function. Remember that the std::map keys must be unique.

So, it first checks whether each key is present in the map. If it is present, the entry will not be inserted, but it returns the iterator for the existing entry. If it is not present, the entry is inserted.

The function has the following variations:

* **insert(pair)** – with this variation, a key-value pair is inserted into the map.
* **insert(start\_itr, end\_itr)** – with this variation, the entries will be inserted within the range defined by start\_itr and end\_itr from another map.

The insert\_or\_assign() function works in the same way as the insert() function, but if the given key already exists in the map, its value will be modified.

### Example 2

#include <map>
#include <iostream>

using namespace std;

int main() {

	map<int, int> m{ {1,3} , {2,4} , {3,5} };

	m.insert({ 5, 6 });
	m.insert({ 1, 8 });

	m.insert_or_assign(1, 6);  
	
	cout << "Key\tElement\n";
	for (auto itr = m.begin(); itr != m.end(); ++itr) {
		cout << itr->first << '\t' << itr->second << '\n';
	}
	return 0;
}

Output:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan3.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan4.png)

Code Explanation:

1. Include the map header file into our code to use its functions.
2. Include the iostream header file into our code to use its functions.
3. Include the std namespace into our code to use its classes without calling it.
4. Call the main() function. The { marks the beginning of the body of the function.
5. Create a map named m where the keys will be integers, and the values will be integers. Three entries have been made into the map.
6. Insert a new entry into the map m. A key of 5 and a value of 6 will be inserted into the map.
7. Trying to make an entry into an already existing key. Since the key 1 already exists in the map, the entry will not be made.
8. Using the insert\_or\_assign() function to insert or modify an existing entry. Since the key 1 already exists, its value will be changed to 6.
9. Print some text on the console. The “\\t” character creates a horizontal space while the “\\n” character moves the mouse cursor to the next line.
10. Use a [for loop](https://www.guru99.com/cpp-for-loop.html) to create an iterator named itr to iterate over the elements of the map named m.
11. Print the values of the map m on the console. The “\\t” character creates a horizontal space between each key and its corresponding value. In contrast, the “\\n” character moves the mouse cursor to the next line after every iteration.
12. End of the body of the for loop.
13. The program must return a value upon successful completion.
14. End of the body of the main() function.

## Searching in a Map

We can use the find() function to search for elements in a map by their keys. If the key is not found, the function returns std::map::end. Otherwise, an iterator of the searched element will be returned.

### Example 3

#include <iostream>
#include <string>
#include <map> 
using namespace std;
int main() {
	map<int, string> Students;
	Students.insert(std::pair<int, string>(200, "Alice"));
	Students.insert(std::pair<int, string>(201, "John"));
	std::map<int, string>::iterator it = Students.find(201);
	if (it != Students.end()) {
		std::cout << endl << "Key 201 has the value: => "<< Students.find(201)->second << '\n';
	}
}

Output:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan5.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan6.png)

Code Explanation:

1. Include the iostream header file into our code to use its functions without getting errors.
2. Include the string header file into our code to use its functions without getting errors.
3. Include the map header file into our code to use its functions without getting errors.
4. Include the std namespace into our code to use its classes without calling it.
5. Call the main() function. The { marks the beginning of the body of the main() function.
6. Create a map named Students whose keys will be integers and values strings.
7. Insert values into the map Students. A key of 200 and a value of Alice will be inserted into the map.
8. Insert values into the map Students. A key of 201 and a value of John will be inserted into the map.
9. Look for the value associated with a key of 201.
10. Use an if statement to check whether the value for the key is found.
11. Print the value of the key alongside some text on the console.
12. End of the body of the if statement.
13. End of the body of the main() function.

## Deleting Data from a Map

We can use the erase() function to delete a value from a map. We simply create an iterator that points to the element to be deleted. The iterator is then passed to the erase() function.

### Example 4

#include <iostream>
#include <string>
#include <map>

using namespace std;
int main() {

	map<std::string, int> my_map;

	my_map.insert(std::make_pair("cow", 1));

	my_map.insert(std::make_pair("cat", 2));

	my_map["lion"] = 3;

	map<std::string, int>::iterator it = my_map.find("cat");

	my_map.erase(it);

	for (map<string, int>::iterator it = my_map.begin(); it != my_map.end(); ++it)

		cout << (*it).first << ": " << (*it).second << endl;

  return 0;
}

Output:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan7.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/072420%5F0655%5FMapinCStan8.png)

Code Explanation:

1. Include the iostream header file into our code to use its functions.
2. Include the string header file into our code to use its functions.
3. Include the map header file into our code to use its functions.
4. Include the std namespace into our code to use its classes without calling it.
5. Call the main() function. The { marks the beginning of the body of the main() function.
6. Create a map named my\_map whose keys will be strings and values integers.
7. Insert values into the map my\_map. A key of Cow and a value of 1 will be inserted into the map.
8. Insert values into the map my\_map. A key of Cat and a value of 2 will be inserted into the map.
9. Add a value 3 into the map my\_map with a key of a lion.
10. Create an iterator to iterate over the map my\_map looking for the key cat.
11. Delete the element pointed to by the iterator.
12. Use an iterator to iterate over the elements of the map my\_map from the start to the end.
13. Print out the contents of the map my\_map on the console.
14. The program must return output upon successful completion.
15. End of the body of the main() function.

## FAQs

🔷 What is the difference between std::map and std::unordered\_map in C++?

std::map keeps keys sorted using a self-balancing binary search tree, giving O(log n) operations. std::unordered\_map uses a hash table for average O(1) lookups but stores keys in no particular order. Choose based on your ordering needs.

🌳 What data structure does a C++ map use internally?

A std::map is typically implemented as a self-balancing binary search tree, most often a red-black tree. This keeps keys in sorted order and guarantees logarithmic time for insertion, deletion, and search operations.

🔑 Can a C++ map store duplicate keys?

No. A std::map holds only unique keys, so inserting an existing key does not overwrite it. When duplicate keys are required, use std::multimap, which allows multiple elements to share the same key value.

🎯 How do you access or update a value in a C++ map?

Use map\_name\[key\] to read or assign a value; the subscript operator inserts a default entry if the key is missing. The at() member throws an exception for absent keys, making it a safer choice.

🔽 How do you sort a C++ map in descending order?

Pass a custom comparator as the third template argument, such as std::map<int, string, std::greater<int>>. The greater comparator orders keys from highest to lowest instead of the default ascending order.

🆚 What is the difference between a map and a set in C++?

A std::map stores key-value pairs and looks up values by key, while a std::set stores only unique keys with no associated value. Both keep elements sorted, but a map associates data with each key.

🤖 Can AI tools generate C++ map code?

Yes. AI coding assistants turn a short prompt or comment into working std::map code, including declarations, insert calls, and iterator loops. Always review the generated key types, ordering, and edge cases before compiling.

🧠 Can GitHub Copilot write C++ std::map operations?

Yes. [GitHub Copilot](https://github.com/features/copilot) suggests map declarations, insert and find calls, and iteration loops as you type. It handles repetitive boilerplate well, though you should still verify key uniqueness and logic before building.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/map-in-cpp-stl.png","url":"https://www.guru99.com/images/map-in-cpp-stl.png","width":"700","height":"250","caption":"Map in C++ STL","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/cpp-map-stl.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/cpp","name":"CPP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/cpp-map-stl.html","name":"Map in C++ Standard Template Library (STL)"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/cpp-map-stl.html#webpage","url":"https://www.guru99.com/cpp-map-stl.html","name":"Map in C++ Standard Template Library (STL)","dateModified":"2026-07-13T13:35:48+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/map-in-cpp-stl.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/cpp-map-stl.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker","description":"I'm Benjamin Walker, an expert in C, C++, and C# programming, providing resources to enhance your coding proficiency and project outcomes.","url":"https://www.guru99.com/author/benjamin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/benjamin-walker-author.png","url":"https://www.guru99.com/images/benjamin-walker-author.png","caption":"Benjamin Walker","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"CPP","headline":"Map in C++ Standard Template Library (STL)","description":"What is std::map? In C++, a MAP is an associative container storing items in a mapped form. Each item in the map is composed of key-value and a mapped value. Two mapped values cannot share the same k","keywords":"bigdata, programming, database, server","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker"},"dateModified":"2026-07-13T13:35:48+05:30","image":{"@id":"https://www.guru99.com/images/map-in-cpp-stl.png"},"copyrightYear":"2026","name":"Map in C++ Standard Template Library (STL)","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between std::map and std::unordered_map in C++?","acceptedAnswer":{"@type":"Answer","text":"std::map keeps keys sorted using a self-balancing binary search tree, giving O(log n) operations. std::unordered_map uses a hash table for average O(1) lookups but stores keys in no particular order. Choose based on your ordering needs."}},{"@type":"Question","name":"What data structure does a C++ map use internally?","acceptedAnswer":{"@type":"Answer","text":"A std::map is typically implemented as a self-balancing binary search tree, most often a red-black tree. This keeps keys in sorted order and guarantees logarithmic time for insertion, deletion, and search operations."}},{"@type":"Question","name":"Can a C++ map store duplicate keys?","acceptedAnswer":{"@type":"Answer","text":"No. A std::map holds only unique keys, so inserting an existing key does not overwrite it. When duplicate keys are required, use std::multimap, which allows multiple elements to share the same key value."}},{"@type":"Question","name":"How do you access or update a value in a C++ map?","acceptedAnswer":{"@type":"Answer","text":"Use map_name[key] to read or assign a value; the subscript operator inserts a default entry if the key is missing. The at() member throws an exception for absent keys, making it a safer choice."}},{"@type":"Question","name":"How do you sort a C++ map in descending order?","acceptedAnswer":{"@type":"Answer","text":"Pass a custom comparator as the third template argument, such as std::map&gt;. The greater comparator orders keys from highest to lowest instead of the default ascending order."}},{"@type":"Question","name":"What is the difference between a map and a set in C++?","acceptedAnswer":{"@type":"Answer","text":"A std::map stores key-value pairs and looks up values by key, while a std::set stores only unique keys with no associated value. Both keep elements sorted, but a map associates data with each key."}},{"@type":"Question","name":"Can AI tools generate C++ map code?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI coding assistants turn a short prompt or comment into working std::map code, including declarations, insert calls, and iterator loops. Always review the generated key types, ordering, and edge cases before compiling."}},{"@type":"Question","name":"Can GitHub Copilot write C++ std::map operations?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot suggests map declarations, insert and find calls, and iteration loops as you type. It handles repetitive boilerplate well, though you should still verify key uniqueness and logic before building."}}]}],"@id":"https://www.guru99.com/cpp-map-stl.html#schema-1142981","isPartOf":{"@id":"https://www.guru99.com/cpp-map-stl.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/cpp-map-stl.html#webpage"}}]}
```
