Common operations of C++ standard template library map

  • 2020-06-12 10:14:30
  • OfStack

1:

map is the associative container of STL, which is stored in the form of ES5en-ES6en, and takes red-black tree (balanced 2-cross lookup tree) as the underlying data structure. It has the function of automatic sorting of data.

The namespace is std and belongs to the header file < map > Note: No < map.h >

2: Common operation

Capacity:

Data for actual data in a: ES23en.size () Maximum number of data in ES25en.map: ES27en.es28EN_ES29en () c. Determine if the container is empty: ES31en. empty()

Modification:

Insert data: ES36en. insert() b. Empty the map element: map.clear () c. Removes the specified element: ES43en.erase (it)

The iterator:

Start pointer: ES50en. begin() b.map tail pointer: ES54en.end () Note: The next position of the last element, similar to NULL, is not the last element of the container

3: store


  map<int, string> map1;
  // methods 1 : 
  map1.insert(pair<int, string>(2, "beijing"));
  // methods 2:
  map1[4] = "changping";
  // methods 3:
  map1.insert(map<int, string>::value_type(1, "huilongguan"));
  // methods 4:
  map1.insert(make_pair<int, string>(3, "xierqi"));

4: traversal


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

5: search


 string value1 = map1[2];
 if (value1.empty())
 {
 cout << "not found" << endl;
 }
 // methods 2
 map<int, string>::iterator it = map1.find(2);
 if (it == map1.end())
 {
 cout << "not found" << endl;
 }
 else
 {
 cout << it->first << ":" << it->second << endl;
 }

6: modify


 // Modify the data 
 map1[2] = "tianjin";

7: remove


 // methods 1
 map1.erase(1);
 // methods 2
 map<int, string>::iterator it1 = map1.find(2);
 map1.erase(it1);

conclusion


Related articles: