I. Introduction
Map is an STL associated container, which is stored in the form of key-value and uses the red/black tree (balanced binary search tree) as the underlying data structure. It Automatically sorts data.
The namespace is STD and the header file <map>
Ii. Common Operations
Capacity:
A. Actual data in map: map. Size ()
B. maximum data volume in map: map. max_size ()
C. Determine whether the container is empty: map. Empty ()
Modify:
A. insert data: map. insert ()
B. Clear the map element: map. Clear ()
C. Delete the specified element: map. Erase (it)
Iterator:
A. Map start pointer: map. Begin ()
B. Map tail pointer: map. End () Note: The next position of the last element, similar to null, is not the last element of the container.
Iii. Storage
1 Map <int, string> map1; 2 3 // Method 1: 4 map1.insert (pair <int, string> (2, "Beijing"); 5 // Method 2: 6 map1 [4] = "Changping"; 7 // method 3: 8 map1.insert (Map <int, string >:: value_type (1, "Huilongguan ")); 9 // Method 4: 10 map1.insert (make_pair <int, string> (3, "xierqi "));
4. Traversal
1 for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)2 {3 cout << it->first << ":" << it->second << endl;4 }
5. Search
1 // method 1 2 string value1 = map1 [2]; 3 if (value1.empty () 4 {5 cout <"not found" <Endl; 6} 7 8 // method 2 9 Map <int, string >:: iterator it = map1.find (2); 10 if (IT = map1.end ()) 11 {12 cout <"not found" <Endl; 13} 14 else15 {16 cout <it-> first <": "<it-> second <Endl; 17}
Vi. Modification
map1[2] = "tianjin";
7. Delete
1 // Method 12 map1.erase (1); 3 4 // Method 25 Map <int, string >:: iterator it1 = map1.find (2); 6 map1.erase (it1 );
STL: Summary of map usage