1. Map insertion operation basics
map
It 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 construction
pair
Object -
insert
Return onepair<iterator, bool>
-
first
: Iterator pointing to an inserted element -
second
: Whether the insertion is successful (bool)
-
Example judgment:
if ( == true) { cout << "Insert successfully! value:" << (*()).second << endl; } else { cout << "Insert failed!" << 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 same
pair<iterator, bool>
2.3 Method 3: Use value_type
(map<int, string>::value_type(3, "Wang Wu"));
Features:
-
value_type
is a typedef defined internally by map, equivalent topair<const Key, T>
- Type-safe, ensure the correct key type
- Return the same
pair<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 keys:
map
Each 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, use
insert
Compare[]
More efficient
6. Practical application suggestions
-
Need to know if the insertion is successful:use
insert
+ Check the return value -
Need to overwrite existing values:use
[]
Operator -
Avoid accidental insertion: Use it first
find
Check if the key exists -
Code simplicity: Priority
make_pair
oremplace
(C++11)
7. Complete code review
#include <map> #include <iostream> using namespace std; int main() { map<int, string> mapStu; // Method 1 auto ret = (pair<int, string>(1, "Zhang San")); if () { cout << "Insert successfully! value:" << ->second << endl; } else { cout << "Insert failed!" << endl; } // Repeat insertion test ret = (pair<int, string>(1, "Xiao Zhang San")); if (!) { cout << "The insertion of Xiao Zhangsan failed!" << endl; } // Method 2 (make_pair(2, "Li Si")); // Method 3 (map<int, string>::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& pair : mapStu) { cout << << ", " << << endl; } system("pause"); return 0; }
8. Extend knowledge
8.1 C++11 emplace
C++11 introduces more efficientemplace
method:
(5, "Qian Qi"); // Construct elements directly in the container,Avoid temporary objects
8.2 Exceptional security
insert
andemplace
Provides 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!