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 key values.

The key values are good for sorting and identifying elements uniquely. The mapped values are for storing content associated with the key. The two may differ in types, but the member type combines them via a pair type that combines both.

In this C++ tutorial, you will learn:

Why use std::map?

Here, are reasons for using map:

  • std:: map stores unique keys only in sorted order based on chosen sorting criteria.
  • It's easy and faster 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 binary trees (balanced).

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 key datatypes and integer as values datatype.

Member types:

The member functions can use the following members 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: 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

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 new key-value pair to a map.
  • find(val)- This function gives the iterator to the val element if it's found. Otherwise, it will return m.end().
  • Erase (iterator position)- This function deletes the item at the position pointed by the iterator.
  • erase(const g)- This function deletes key-value g from a map.
  • Clear ()-This function deletes all items from a map.

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:

Here is a screenshot of the code:

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.

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's present, the entry will not be inserted, but it returns the iterator for the existing entry. If it's 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_assing() function works in the same way as 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:

Here is a screenshot of the code:

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 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 a loop.
  13. The program must return 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 isn't found, the function returns std::map::end. Otherwise, an iterator of the searched element will be returned.

Example 2:

#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:

Here is a screenshot of the code:

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 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 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 3:

#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:

Here is a screenshot of the code:

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.

Summary:

  • A map is an associative container that stores items in a mapped form.
  • Each item in the map has a key value and a mapped value.
  • In a map, two mapped values cannot share key values.
  • The key values help in sorting and identifying elements uniquely.
  • The mapped values help in storing content associated with the key.
  • C++ map stores unique keys in sorted order.
  • To work with C++ map, we create an iterator to iterate over the elements.
  • With the iterator, we can perform tasks like searching and deleting items from the map.

 

YOU MIGHT LIKE: