C++ Map Insert Function - C++ Programming Tutorial
C++ Course / STL Set & Map / C++ Map Insert Function

C++ Map Insert Function

BLUF: Mastering C++ Map Insert Function 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 Insert Function

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

In C++, the Standard Template Library (STL) offers the std::map as an associative container that organizes key-value pairs based on the key's order. This is an inherent member function of the map container and is frequently used for adding elements into the map. Within the map container, it is essential that each key value is distinct, leading to automatic sorting of elements in ascending order.

In C++, the insert method in a map is frequently used to add a fresh element into the map. Since map keys must be unique, when inserting, the function first verifies if the specified key already exists in the map container. If the key is found in the map, it will not be added, and the function will return the iterator pointing to the existing key; otherwise, a new element will be added to the map.

Syntax:

It has the following syntax:

Example

single element (1)     pair<iterator,bool> insert (const value_type& val);   //Until C++ 11  

  

with hint (2)   iterator insert (iterator position, const value_type& val);   //Until C++ 11  

  

range (3)   template <class InputIterator>  

           void insert (InputIterator first, InputIterator last);        //Until C++ 11  

  

single element (1)  pair<iterator,bool> insert (const value_type& val);  

          template <class P> pair<iterator,bool> insert (P&& val); //Since C++ 11  

              

with hint (2)   iterator insert (const_iterator position, const value_type& val);  

           template <class P> iterator insert (const_iterator position, P&& val);  

  

range (3)   template <class InputIterator>  

           void insert (InputIterator first, InputIterator last); //Since C++ 11  

  

initializer list (4)    void insert (initializer_list<value_type> il);   //Since C++ 11

In this syntax,

  • val: It represents a key value to insert in the map.
  • position: It represents the hint for the position to insert the element.
  • first: It represents the beginning of the range to insert.
  • last: It represents the end of the range to insert.
  • il: It represents an initializer list.
  • Return Value

It provides a boolean pair to signify if the insertion occurred and gives back an iterator indicating the newly added element.

Why do we use the map insert function in C++?

There are several scenarios where we can use the insert function in C++. Some of them are as follows:

  • In the C++ programming language, the map::insert function will only insert if the key does not already exist. If the key exists, the insertion will fail, and the old value will be preserved.
  • The map insert function provides the details whether the insertion took place or not, and where, if it did. It can also be useful for checking for duplicates.
  • This function also provides the hint and range-based overloads that are effective for insertion operations.
  • C++ Simple Map insert Function Example

Let's consider a basic illustration of adding elements to a map using the insert function in C++.

Example

Example

#include <iostream>  

#include <map>  

  using namespace std;    //using standard namespace

  int main() {    //main function

   map<char, int> m = {  

            {'a', 1},  

            {'b', 2},  

            {'c', 3},  

            };  

     // inserting new element  

   m.insert (pair<char, int>('d', 4));  

   m.insert (pair<char, int>('e', 5));  

     cout << "The map contains the following elements:" << endl;  

     for (auto it = m.begin (); it != m.end(); ++it)  

      cout << it->first << " = " << it->second << endl;  

     return 0;  

}

Output:

Output

The map contains the following elements:

a = 1

b = 2

c = 3

d = 4

e = 5

Explanation:

In this instance, a map (m) has been established with an initial set of three key-value pairs. Subsequently, the insert method has been employed to add additional elements ('d', 4 and 'e', 5) to the map. Following that, a for loop is utilized to iterate through the map and display all key-value pairs in a sorted manner.

C++ Map insert Function Example with the Hint Position

Let's explore a basic illustration of inserting an element at a specific location using the map insert method in C++.

Example

Example

#include <iostream>  

#include <map>  

  using namespace std;    //using standard namespace

  int main (void) {     //main function

   map <char, int> m = {  

            {'b', 2},  

            {'c', 3},  

            {'d', 4},  

            };  

   //inserting element with the given position  

   m.insert ( m.begin (), pair<char, int> ('a', 1));    

   m.insert ( m.end (), pair<char, int> ('e', 5));  

    cout << "The map contains the following elements: " << endl;  

     for ( auto it = m.begin (); it != m.end (); ++it)  

      cout << it->first << " = " << it->second << endl;  

     return 0;  

}

Output:

Output

The map contains the following elements:

a = 1

b = 2

c = 3

d = 4

e = 5

Explanation:

In this instance, a map named m is generated with three key-value pairs set at the start. Subsequently, additional elements are added at specific positions: {'a', 1} at the beginning and {'e', 5} at the end. The program then loops through and displays all key-value pairs in a sorted manner.

C++ Map insert Function Example using a Range of Elements

Let's consider a basic illustration of adding elements within a range using the map insert method in C++.

Example

Example

#include <iostream>  

#include <map>  

  using namespace std;    //using standard namespace

  int main () {     //main function

     map <char, int > m1 = {  

            { 'a', 1 },  

            { 'b', 2 },  

            { 'c', 3 },  

            { 'd', 4 },  

            { 'e', 5 },  

            };  

  map <char, int> m2;  // creating new map m2  

m2.insert (m1.begin (), m1.end ());   //inserting the elements of m1 to m2  

     cout << "The map contains the following elements: " << endl;  

     for (auto it = m2.begin (); it != m2.end (); ++it)  

      cout << it->first << " = " << it->second << endl;  

     return 0;  

}

Output:

Output

The map contains the following elements:

a = 1

b = 2

c = 3

d = 4

e = 5

Explanation:

In this instance, we've established a map named m1 with five elements, while map m2 remains void. Subsequently, we've employed the insert method to transfer the elements from the start to the end of m1 into m2, followed by displaying the contents of the m2 map.

C++ Map insert Function Example with Different Methods

Let's consider a scenario to demonstrate the utilization of the map insert method using various approaches in the C++ programming language.

Example

Example

#include <iostream>

#include <map>

#include <string>

using namespace std;   //using standard namespace

int main() {    //main function

    // Creating a map to store student roll numbers and names

    map<int, string> students = {

        {101, "Johnson"},

        {102, "Peter"},

        {103, "Robert"}

    };

    cout << "Initial Student Records:\n";

    for (auto &entry : students)

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

    cout << "\n--- Attempting Duplicate Key Insertion ---\n";

    auto duplicate = students.insert({103, "Duplicate Chirag"});

    if (!duplicate.second)

        cout << "Duplicate key '103' not inserted. Existing value: " << duplicate.first->second << endl;

    cout << "\n--- Hint-Based Insertion ---\n";

    auto itHint = students.find(104);

    students.insert(itHint, {105, "Alisha"}); // Hint helps optimize insertion

    cout << "Inserted element 105 using hint.\n";

    cout << "\n--- Batch Insertion Using the Initializer List ---\n";

    students.insert({{106, "Farhan"}, {107, "Gauri"}, {108, "Harsh"}});

    cout << "Multiple elements inserted successfully.\n";

    cout << "\n--- Inserting Elements from Another Map ---\n";

    map<int, string> newStudents = {

        {201, "Ira"},

        {202, "Jay"},

        {203, "Kavya"}

    };

    students.insert(newStudents.begin(), newStudents.end());

    cout << "Copied all elements from newStudents map.\n";

    cout << "\n--- Final Map Contents ---\n";

    for (auto &entry : students)

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

    cout << "\n--- Summary ---\n";

    cout << "Total Students in the Map: " << students.size() << endl;

    cout << "Is key 103 present: " << (students.count(103) ? "Yes" : "No") << endl;

    cout << "Is key 110 present: " << (students.count(110) ? "Yes" : "No") << endl;

    return 0;

}

Output:

Output

Initial Student Records:

101 : Johnson

102 : Peter

103 : Robert

--- Attempting Duplicate Key Insertion ---

Duplicate key '103' not inserted. Existing value: Robert

--- Hint-Based Insertion ---

Inserted element 105 using hint.

--- Batch Insertion Using Initializer List ---

Multiple elements inserted successfully.

--- Inserting Elements from Another Map ---

Copied all elements from newStudents map.

--- Final Map Contents ---

101 : Johnson

102 : Peter

103 : Robert

105 : Alisha

106 : Farhan

107 : Gauri

108 : Harsh

201 : Ira

202 : Jay

203 : Kavya

--- Summary ---

Total Students in the Map: 10

Is key 103 present: Yes

Is key 110 present: No

Explanation:

In this code snippet, we generate various data types by utilizing the map::insert method. Initially, it demonstrates the scenario of inserting a duplicate key (key 103) as maps strictly enforce unique keys. Subsequently, we perform an insertion with a hint to efficiently add a new element, then proceed with a batch insertion using an initializer list to add multiple entries simultaneously. Lastly, elements are added from a different map through a range insertion operation, after which the entire map contents, overall size, and key presence are exhibited in the console output.

Features of the map insert function in C++

There are several features of the map insert function in C++. Some of them are as follows:

  • In C++, the map insert function allows us to insert elements in the form of key-value pairs within a map container.
  • It returns a pair that consists of an iterator and a Boolean, which indicates the success or failure of the insertion.
  • It enables us to use several overloads, such as single-element insertion, range insertion, hint-based insertions, and initializer list insertion.
  • We can easily insert elements from any map or container using iterator ranges with the help of the map insert function in C++.
  • The map insert function supports type-safe operations, and it works with the user-defined data types.
  • Conclusion

In summary, the C++ map::insert method is an inherent member function of the map container within the C++ Standard Template Library (STL). It enables developers to efficiently add new key-value pairs to a map while preserving the order and uniqueness of keys. Since the standard library utilizes a balanced binary search tree (usually a Red-Black Tree) for std::map, the time complexity of each insertion operation is logarithmic.

C++ Map insert Function FAQs

The primary purpose of the insert function in a C++ map container is to add a new key-value pair into the map.

In C++, the insert method is frequently used to securely append new key-value pairs to a map, ensuring key uniqueness and preserving the order of elements automatically.

The insert function in C++ handles duplicate keys by not inserting a new key-value pair if a key already exists in the map.

If we attempt to add a key that is already present in the map, it will not replace the existing value. Instead, the insert method will return a pair indicating that the insertion was unsuccessful, with the boolean (second) value set to false.

3) In what scenarios should we opt for utilizing the insert function over the subscript operator ()?

The map insert method proves to be quite beneficial when we need to securely introduce new elements without jeopardizing any existing values in use. On the other hand, the [key] = value operator is particularly useful when our intention is to intentionally update the previous key with a new value.

Is the sequence of insertion significant in determining the storage arrangement within a map in C++?

No. The map container will consistently organize the elements automatically in ascending order based on the keys (by default). The order in which elements are inserted will not impact the eventual order of elements.

The insert function in C++ maps is utilized to add a new key-value pair into the map.

The insert method in C++ is frequently employed to add fresh key-value pairs in the map, guaranteeing unique keys and automatic sorting of elements within the map. This function facilitates the secure growth of the map, preventing duplicate entries and maintaining orderly arrangement.

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