C++ Map - C++ Programming Tutorial

C++ Map

BLUF: Mastering C++ Map is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Map

C++ is renowned for its efficiency. Learn how C++ Map enables low-level control and high-performance computing in the tutorial below.

In C++, maps are an essential component of the STL (Standard Template Library). Maps serve as associative containers that hold key-value pairs in sorted order, ensuring each key is unique and unalterable once inserted or deleted. However, the values linked to these keys are modifiable.

Syntax

It has the following syntax:

Example

map<key_type, value_type, comp> t;

Parameter

It has the following parameters:

  • Key_type: The key data type to be stored in the map.
  • Value_type: The data type of value to be stored in the map.
  • compare: A comparison class that takes two arguments of the same type bool and returns a value. This argument is optional, and the binary predicate less<"key"> is the default value.
  • t: It represents the name assigned to the map.
  • C++ Algorithm Example

Let's consider an example to demonstrate the Algorithm Standard Template Library (STL) in C++.

Example

Example

#include <string.h>  

#include <iostream>  

#include <map>  

#include <utility>  

using namespace std;  

int main()  

{  

  map<int, string> Employees;  

   // 1) Assignment using array index notation  

   Employees[101] = "Alice";  

Employees[105] = "John";  

Employees[103] = "Dolly";  

 Employees[104] = "Deep";  

   Employees[102] = "Bob";  

   cout << "Employees[104]=" << Employees[104] << endl << endl;  

   cout << "Map size: " << Employees.size() << endl;  

   cout << endl << "Natural Order:" << endl;  

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

   {  

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

   }  

   cout << endl << "Reverse Order:" << endl;  

   for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend(); ++ii)  

   {  

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

   }  

}

Output:

Output

Employees[104]=Deep

Map size: 5

Natural Order:

101: Alice

102: Bob

103: Dolly

104: Deep

105: John

Reverse Order:

105: John

104: Deep

103: Dolly

102: Bob

101: Nikita

Operations on a Map Function

There are several operations performed on a Map Function. These operations are as follows:

  • Accessing Elements on a Map
  • Changing Values in a Map
  • Adding elements to a Map
  • Elements with Equal Keys
  • Removing Elements from a map
  • Finding the Size of a Map
  • Checking if a map is empty
  • Loop Through a Map

Now, we will explore each of these operations individually.

Accessing Elements on a Map

Maps, in contrast to arrays or vectors, do not support access via index numbers due to their storage of data as key-value pairs rather than in a sequential manner. To retrieve a value from a map, we need to utilize the respective key enclosed within square brackets .

C++ Accessing Elements Example

Let's explore Accessing Elements in a C++ Map.

Example

Example

#include <iostream>

#include <map>  //using map header file

using namespace std;   //using standard namespace

int main()   //Main Function

{

    map<string, int> employee = {

        {"Alice", 5},

        {"Bob", 3},

        {"Charlie", 8}

    };

    cout << "Alice has " << employee["Alice"] << " years of experience.\n";   

    cout << "Bob has " << employee["Bob"] << " years of experience.\n";

    cout << "Charlie has " << employee.at("Charlie") << " years of experience.\n";

    try 

    {

        cout << "David has " << employee.at("David") << " years of experience.\n";

    }

    catch (const out_of_range& e) 

    {

        cout << "Error: 'David' is not found in the employee list.\n";  //print the error

    }

    return 0;

}

Output:

Output

Alice has 5 years of experience.

Bob has 3 years of experience.

Charlie has 8 years of experience.

ERROR!

David has Error: 'David' is not found in the employee list.

Explanation

In this instance, we employ a map function to store names of employees as keys along with their corresponding years of experience as values. It fetches and displays the specific employees' years of experience by employing both the notation and the .at method.

Changing Values in a Map

In C++, we have the capability to modify the value associated with a particular key in a map by assigning a fresh value to that key. This functionality comes in handy when there is a requirement to update current entries, like modifying a salary, age, or score.

C++ Example to Change Values in a Map

Let's consider an example to demonstrate the modification of values in a map in C++.

Example

Example

#include <iostream>

#include <map>

using namespace std;   //using standard namespace

int main() {   //Main Function

    map<string, int> employee_Age = {

        {"Joseph", 30},

        {"Jacob", 32},

        {"John", 28}

    };

    employee_Age["Joseph"] = 29;

    employee_Age.at("Jacob") = 36;

    employee_Age["Dia"] = 26;

    employee_Age["Adarsh"] = 32;

    employee_Age.insert({"James", 27});

    employee_Age.insert({"Wesly", 31});

    cout << "Updated Employee Ages:\n";

    for (const auto& [name, age] : employee_Age)

    {

        cout << name << " is " << age << " years old.\n";

    }

    return 0;

}

Output:

Output

Updated Employee Ages:

Adarsh is 32 years old.

Dia is 26 years old.

Jacob is 36 years old.

James is 27 years old.

John is 28 years old.

Joseph is 29 years old.

Wesly is 31 years old.

Explanation

In this instance, we are organizing and handling employee names and ages through a map data structure. This demonstrates the process of modifying existing data using both and .at, as well as adding new entries with and .insert. To conclude, it employs a range-based for loop to exhibit an updated roster of employees alongside their latest ages.

Adding elements to a Map

The square brackets or the .insert method is employed for inserting elements into a map.

  • Square Brackets : This method enables the addition of new elements to the map or modification of the value associated with an existing key. When a key is not present, it adds a new entry with the provided value. In case the key already exists, it updates the current value.
  • .insert Function: The .insert function is responsible for creating fresh key-value pairs within the map. It does not overwrite keys that are already present. If the map already contains a specific key, the insertion operation is disregarded. This function is beneficial when the objective is to ensure that only new keys are added while leaving existing ones unchanged.
  • C++ Example to Add Elements to a Map

Let's consider an illustration to Insert elements into a Map in C++.

Example

Example

#include <iostream>

#include <map>

using namespace std;   //Using Standard Namespace

int main()   //Main Function

{

    map<string, int> student_Age = {

        {"Arjun", 16},

        {"Fatima", 17},

        {"Luca", 15}

    };

    student_Age["Meera"] = 16;

    student_Age["Noah"] = 17;

    student_Age.insert({"Zara", 15});

    student_Age.insert({"Leo", 16});

    cout << "Student Age Database:\n";

    for (const auto& [name, age] : student_Age) 

    {

        cout << name << " is " << age << " years old.\n";

    }

    return 0;

}

Output:

Output

Student Age Database:

Arjun is 16 years old.

Fatima is 17 years old.

Leo is 16 years old.

Luca is 15 years old.

Meera is 16 years old.

Noah is 17 years old.

Zara is 15 years old.

Explanation

In this instance, we establish a map that holds student names as keys and their corresponding ages as values. It demonstrates two techniques for inserting elements into the map: employing square brackets () to append or modify entries and utilizing the .insert method to add fresh entries without replacing existing ones.

Elements with Equal Keys

In C++, a map cannot contain duplicate keys. Every key within a map must be distinct, so attempting to add an element with a pre-existing key using the .insert method will be ignored. While values can be identical, keys must be unique.

C++ Elements with Equal Keys Example

Let's consider an example to demonstrate Elements with Identical Keys in C++.

Example

Example

#include <iostream>

#include <map>

using namespace std;   //using standard namespace

int main() {   //Main Function

    map<string, int> studentmarks;

    studentmarks.insert({"John", 85});

    studentmarks.insert({"Joseph", 90});

    studentmarks.insert({"Jacob", 78});

    auto ans = studentmarks.insert({"John", 95});

    if (!ans.second) 

    {

        cout << "Insertion failed: Key 'John' already exists with score " 

             << ans.first->second << endl;

    }

    studentmarks["John"] = 95;

    cout << "Final Student Marks:\n";

    for (const auto& entry : studentmarks) 

    {

        cout << entry.first << ": " << entry.second << endl;

    }

    return 0;

}

Output:

Output

Insertion failed: Key 'John' already exists with score 85

Final Student Marks:

Jacob: 78

John: 95

Joseph: 90

Explanation

In this instance, a map is employed to store student names and their corresponding grades, guaranteeing uniqueness for each name (key). An attempt is made to add "John" a second time, but it fails as the key already exists, as indicated by a notification. Subsequently, the code modifies John's grade through direct assignment and showcases the ultimate scores for all students.

Removing Elements from a Map

In C++, the .erase(key) function is employed to eliminate a particular element. Subsequently, you can invoke the .clear method to delete all elements. These functions streamline the process of handling and modifying your data set in practical scenarios.

C++ Example to Remove Elements from a Map

Let's consider a scenario to demonstrate the Deletion of Elements from a map in C++.

Example

Example

#include <iostream>

#include <map>

using namespace std;   //Using Standard Namespace

int main()   //Main Function

{

    map<string, int> employee_ages;

    employee_ages.insert({"Joseph", 29});

    employee_ages.insert({"John", 36});

    employee_ages.insert({"Jacob", 42});

    employee_ages.insert({"David", 25});

    cout << "Original Employee Records:\n";

    for (const auto& entry : employee_ages) 

    {

        cout << entry.first << ": " << entry.second << endl;

    }

    employee_ages.erase("John");

    cout << "After Removing 'John':\n";

    for (const auto& entry : employee_ages)

    {

        cout << entry.first << ": " << entry.second << endl;

    }

    employee_ages.clear();

    cout << "After Clearing All Records:\n";

    if (employee_ages.empty()) 

    {

        cout << "No records found.\n";

    }

    return 0;

}

Output:

Output

Original Employee Records:

David: 25

Jacob: 42

John: 36

Joseph: 29

After Removing 'John':

David: 25

Jacob: 42

Joseph: 29

After Clearing All Records:

No records found.

Explanation

In this instance, we generate a mapping of employee names along with their respective ages and subsequently exhibit the complete roster. The process involves employing the .erase method to eliminate the record corresponding to "John" before showcasing the updated list. Ultimately, the code utilizes .clear to eradicate all entries and employs .empty to verify that the map is devoid of any records.

Finding the Size of a Map

In C++, the .size method of a map gives back the total count of key-value pairs currently held within it. In real-world scenarios, it is commonly employed to tally the number of entries, like users, products, and employees.

C++ Example to find the size of a Map

Let's explore determining the Size of a Map in C++.

Example

Example

#include <iostream>

#include <map>

#include <string>

int main() 

{

    std::map<int, std::string> Employee;

    Employee[101] = "Mahesh";

    Employee[102] = "Johnson";

    Employee[103] = "Akshitha";

    Employee[104] = "Supriya";

    std::cout << "Total number of employees are: " << Employee.size() << std::endl;

    return 0;

}

Output:

Output

Total number of employees are: 4

Explanation

This C++ code snippet utilizes an STL map to store employee names corresponding to their ID numbers. By employing bracket notation, it inserts four new employee entries into the map. Subsequently, it retrieves the total count of employees by invoking the.size method of the map.

Checking if a Map is Empty

In C++, the .empty function checks if a map contains any key-value pairs. It will return true (1) if the map is empty, and false (0) if it's not. Likewise, the .count(key) method checks if a specific key is present in the map. It will return 1 if the key exists, and 0 if it doesn't.

C++ Example to Check a Map is Empty

Let's consider an example to verify whether a map is empty or not in C++.

Example

Example

#include <iostream>

#include <map>

#include <string>

using namespace std;   //using standard namespace

int main()   //Main Function

{

    map<std::string, int> inventory;

    if (inventory.empty()) 

    {

        cout << "The inventory is currently empty." << endl;

    }

    inventory["Laptops"] = 33;

    inventory["Key boards"] = 50;

    inventory["Desktops"] = 60;

    cout << "Inventory empty status: " << inventory.empty() << endl;

    cout << "Is 'Laptops' in stock? " << inventory.count("Laptops") << endl;

    cout << "Is 'Cell Phones' in stock? " << inventory.count("Cell Phones") << endl;

    return 0;

}

Output:

Output

The inventory is currently empty.

Inventory empty status: 0

Is 'Laptops' in stock? 1

Is 'Cell Phones' in stock? 0

Explanation

In this instance, we create a map called inventory to depict stock items along with their quantities. Initially, it verifies if the inventory is devoid of any items and subsequently includes three products with their corresponding quantities. Ultimately, the.count method is employed to ascertain if the inventory remains empty and if certain products like "Laptops" and "Cell Phones" are in stock.

Loop Through a Map

In C++, a map can be traversed using a range-based for loop along with the auto keyword. Every element in the map represents a key-value pair that can be accessed using the .first method for the key and .second for the corresponding value. By default, maps arrange keys in ascending order, unless specified otherwise, like using greater for a descending order arrangement.

C++ Example to Loop through a Map

Let's consider a scenario to demonstrate Iterating Over a Map in C++.

Example

Example

#include <iostream>

#include <map>

#include <string>

#include <functional>

using namespace std;  //using standard namespace

int main()  //Main function

{

    map< string, int, greater< string>> check_in;

    check_in["Akshay"] = 25;

    check_in["Sanjay"] = 27;

    check_in["Prasad"] = 30;

    for (auto q : check_in) 

    {

cout << q.first << " attended: " << q.second << " days" << endl;

    }

    return 0;

}

Output:

Output

Sanjay attended: 27 days

Prasad attended: 30 days

Akshay attended: 25 days

Explanation

In this instance, a map called check_in is created to store participants' names and their respective attendance durations. It employs the greater function to arrange the map in reverse order according to the names. The for loop automatically cycles through the map, displaying each name along with the corresponding attendance days.

Member Functions

Below is the compilation of all member methods of the map data structure:

Constructor/Destructor

The provided table displays various constructor and destructor functions utilized in C++ Map.

Functions Description
constructors Construct map
destructors Map destructor
operator= Copy elements of the map to another map.

Iterators

The provided table displays various iterator functions commonly utilized in C++ Map.

Functions Description
begin Returns an iterator pointing to the first element in the map.
cbegin Returns a const iterator pointing to the first element in the map.
end Returns an iterator pointing to the past-end.
cend Returns a constant iterator pointing to the past-end.
rbegin Returns a reverse iterator pointing to the end.
rend Returns a reverse iterator pointing to the beginning.
crbegin Returns a constant reverse iterator pointing to the end.
crend Returns a constant reverse iterator pointing to the beginning.

Capacity

The provided table displays various capacity functions utilized in C++ Map data structure.

Functions Description
empty Returns true if map is empty.
size Returns the number of elements in the map.
max_size Returns the maximum size of the map.

Element Access

The presented table displays various element retrieval functions utilized in C++ Map data structure.

Functions Description
operator[] Retrieve the element with given key.
at Retrieve the element with given key.

Modifiers

The provided table displays various modifier functions utilized in C++ Map.

Functions Description
insert Insert element in the map.
erase Erase elements from the map.
swap Exchange the content of the map.
clear Delete all the elements of the map.
emplace Construct and insert the new elements into the map.
emplace_hint Construct and insert new elements into the map by hint.

Observers

The provided table displays various modifier functions utilized in C++ Map.

Functions Description
key_comp Return a copy of key comparison object.
value_comp Return a copy of value comparison object.

Operations

The provided table displays various operation functions utilized in C++ Map data structure.

Functions Description
find Search for an element with given key.
count Gets the number of elements matching with given key.
lower_bound Returns an iterator to lower bound.
upper_bound Returns an iterator to upper bound.
equal_range Returns the range of elements matches with given key.

Allocator

The provided table displays various allocator functions utilized in C++ Map.

Functions Description
get_allocator Returns an allocator object that is used to construct the map.

Non-Member Overloaded Functions

The provided table displays various Overloaded functions for non-members that are utilized in C++ Map.

Functions Description
operator== Checks whether the two maps are equal or not.
operator!= Checks whether the two maps are equal or not.
operator_PRESERVE20__ Checks whether the first map is greater than other or not.
operator>= Checks whether the first map is greater than equal to other or not.
swap() Exchanges the element of two maps.

C++ Map MCQs

1) In C++, which function checks whether a std::map is empty?

  • .count
  • .clear
  • .size
  • .empty

2) Which of the following will return the number of entries in a C++ map containing a certain key?

  • .count
  • .find
  • .at
  • .size

3) In C++, how do the different elements of a std::map get arranged by default?

  • Descending Order
  • Random order
  • Ascending order.
  • user-defined order

4) What is the purpose of the.insert function in a C++ std::map?

  • Returns the number of elements in the map
  • Replaces an existing element
  • Clears all elements from the map
  • Adds a new element if the key does not exist

Adds a fresh element in case the key is absent

5) What is the purpose of the std::greater functor in a std::map?

  • To remove elements greater than a specified key
  • To sort the map in descending order
  • To sort the map in ascending order
  • To ensure all keys are unique

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience