SoFunction
Updated on 2025-05-19

Detailed explanation of the operation method of C++ map container insertion

1. Map insertion operation basics

mapIt is an associated container in C++ STL, storing key-value pairs. There are four main ways to insert elements, each with its characteristics:

1.1 Header files and statements

#include <map>
using namespace std;
map<int, string> mapStu;  // The key isint,The value isstring

2. Detailed explanation of four insertion methods

2.1 Method 1: Insert after constructing the pair

pair<map<int, string>::iterator, bool> ret = 
    (pair<int, string>(1, "Zhang San"));

Features

  • Explicit constructionpairObject
  • insertReturn onepair<iterator, bool>
    • first: Iterator pointing to an inserted element
    • second: Whether the insertion is successful (bool)

Example judgment

if ( == true) {
    cout &lt;&lt; "Insert successfully! value:" &lt;&lt; (*()).second &lt;&lt; endl;
} else {
    cout &lt;&lt; "Insert failed!" &lt;&lt; endl;  // Fails when the key already exists}

Notice:formap, If the key already exists, the insertion will fail and the original value will not be overwritten.

2.2 Method 2: Use make_pair

(make_pair(2, "Li Si"));

advantage

  • The syntax is more concise, without explicitly specifying template parameters
  • Automatically deduce pair type
  • Return the samepair<iterator, bool>

2.3 Method 3: Use value_type

(map&lt;int, string&gt;::value_type(3, "Wang Wu"));

Features

  • value_typeis a typedef defined internally by map, equivalent topair<const Key, T>
  • Type-safe, ensure the correct key type
  • Return the samepair<iterator, bool>

2.4 Method 4: Use the [] operator

mapStu[4] = "Zhao Liu";      // InsertmapStu[4] = "Xiao Zhao Liu";    // Revise

Key Features

  • Find + Insert/Modify: First find out whether the key exists. If it does not exist, it will be inserted. If it exists, it will be modified.
  • Possible insertion: It will be automatically inserted when accessing non-existent keys
string strName = mapStu[8];  // key8It will be automatically inserted when it does not exist

Return value: The reference to the return value can be modified directly

Special usage

mapStu[6] = mapStu[5];  // Copy the value of key 5 to key 6mapStu[7] = mapStu[4];  // Copy key4The value to the key7

3. Comparison of four ways

characteristic Method 1 (pair) Method 2 (make_pair) Method three (value_type) Method 4 ([])
Syntax Complexity high middle high Low
Return value pair<iter,bool> pair<iter,bool> pair<iter,bool> Value reference
Behavior when a key exists Not covered Not covered Not covered cover
Possible insertion no no no yes
Type safety high middle Highest Low
performance medium medium medium A little faster

4. Traverse the map content

for (map<int, string>::iterator it = (); 
     it != (); it++) {
    cout << it->first << ", " << it->second << endl;
}

Or use C++11 range for loop:

for (const auto& pair : mapStu) {
    cout <<  << ", " <<  << endl;
}

5. Key considerations

  • Uniqueness of keysmapEach key can only appear once, and repeated insertion will fail
  • Automatic sorting: Automatically arrange element keys in ascending order
  • []Risk of Operator
    • New elements may be inserted accidentally
    • When accessing non-existent keys, new elements are created with default values.
  • Performance considerations
    • Average time complexity of insertion operation O(log n)
    • For keys that are not known to exist, useinsertCompare[]More efficient

6. Practical application suggestions

  • Need to know if the insertion is successful:useinsert+ Check the return value
  • Need to overwrite existing values:use[]Operator
  • Avoid accidental insertion: Use it firstfindCheck if the key exists
  • Code simplicity: Prioritymake_pairoremplace(C++11)

7. Complete code review

#include &lt;map&gt;
#include &lt;iostream&gt;
using namespace std;
int main() {
    map&lt;int, string&gt; mapStu;
    // Method 1    auto ret = (pair&lt;int, string&gt;(1, "Zhang San"));
    if () {
        cout &lt;&lt; "Insert successfully! value:" &lt;&lt; -&gt;second &lt;&lt; endl;
    } else {
        cout &lt;&lt; "Insert failed!" &lt;&lt; endl;
    }
    // Repeat insertion test    ret = (pair&lt;int, string&gt;(1, "Xiao Zhang San"));
    if (!) {
        cout &lt;&lt; "The insertion of Xiao Zhangsan failed!" &lt;&lt; endl;
    }
    // Method 2    (make_pair(2, "Li Si"));
    // Method 3    (map&lt;int, string&gt;::value_type(3, "Wang Wu"));
    // Method 4    mapStu[4] = "Zhao Liu";
    mapStu[4] = "Xiao Zhao Liu";  // Coverage    // Special usage    mapStu[6] = mapStu[5];  // copy    mapStu[7] = mapStu[4];  // copy    // traversal output    for (const auto&amp; pair : mapStu) {
        cout &lt;&lt;  &lt;&lt; ", " &lt;&lt;  &lt;&lt; endl;
    }
    system("pause");
    return 0;
}

8. Extend knowledge

8.1 C++11 emplace

C++11 introduces more efficientemplacemethod:

(5, "Qian Qi");  // Construct elements directly in the container,Avoid temporary objects

8.2 Exceptional security

insertandemplaceProvides strong exception guarantee: if insertion fails, the container remains unchanged.

8.3 Performance optimization

For large batch inserts:

If the keys are known to be ordered, you can insert them using the prompt position:

(hint_iterator, make_pair(10, "Sun Ba"));

Or build vector first and then insert batch

This is the article about C++ map container: Insert operation. For more related content on inserting C++ map containers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!