About the map:

Map is an associated container of the STL (Chinese Standard Template Library).

  • You can map any base type to any base type. Int array[100] defines a mapping from int to int.
  • Map provides one-to-one data processing. Key-value pairs can be of user-defined types. The first pair is called a keyword, and the second one is the keyword value
  • The map is automatically sorted internally

The use of the map

1. Import package:

#include<map>
Copy the code

2. The definition of the map

map<type1name,type2name> maps; // The first is the key type, and the second is the value type

map<string.int> maps;
Copy the code

3. Access to elements in the map container

  • Access by subscript
maps['c'] =5;
Copy the code
  • Accessing a map through an iterator can use it->first to access keys and it->second to access values
#include<map>
#include<iostream>
using namespace std;
int main(a)
{
   map<char.int>maps;
   maps['d'] =10;
   maps['e'] =20;
   maps['a'] =30;
   maps['b'] =40;
   maps['c'] =50;
   maps['r'] =60;
   for(map<char.int>::iterator it=mp.begin(); it! =mp.end(); it++) {cout<<it->first<<""<<it->second<<endl;
   }
   return 0;
}
Copy the code

4. Common usage of MAP

  • Insert maps. The insert ()
// Define a map object
map<int.string> m;
 
// Use the insert function to insert the pair
m.insert(pair<int.string> (111."kk"));
 
// Insert value_type data with insert
m.insert(map<int.string>::value_type(222."pp"));
 
// Insert an array
m[123] = "dd";
m[456] = "ff";
Copy the code
  • Maps.find () finds an element
//find(key): returns an iterator that maps keys
map<string.int>::iterator it;
it=maps.find("123");
Copy the code
  • Maps. The clear () to empty
  • Maps.erase () removes an element
// Delete iterator
it = maps.find("123");
maps.erase(it);

// Delete the keyword
int n = maps.erase("123"); // Return 1 if deleted, 0 otherwise

// Delete with iterator range: empty the entire map
maps.erase(maps.begin(), maps.end());
// equivalent to mapStudent.clear()
Copy the code
  • Maps. Szie length ()
intlen=maps.size(); Access to themapThe number of mappings inCopy the code
  • Maps.begin () returns an iterator to the map header
  • Maps.end () returns an iterator pointing to the end of the map
/ / iteration
map< string.int>::iterator it;
for(it = maps.begin(); it ! = maps.end(); it++)cout<<it->first<<""<<itr->second<<endl;// Outputs the key and value values
Copy the code
  • Maps.rbegin () returns a reverse iterator to the end of the map
  • Maps.rend () returns a reverse iterator to the map header
// Reverse iteration
map<string.int>::reverse_iterator it;
for(it = maps.rbegin(); it ! = maps.rend(); it++)cout<<it->first<<' '<<it->second<<endl;
Copy the code
  • Maps.empty () determines whether it is empty
  • Maps.swap () swaps two maps

The original connection