Example analysis of basic map usage and nesting method in c++

  • 2020-04-02 02:58:34
  • OfStack

This article illustrates the basic use and nesting of maps in c++. Share with you for your reference. Specific analysis is as follows:

The map container in C++ provides a key-value pair container, and the only difference between map and multimap is that multiple allows a key to correspond to multiple values. This article will summarize the basic map usage and nesting examples.

1. Basic usage of map

1. The header files

#include <map>

Definition 2.

map<int,int> my_Map; // Notice the int and int It could be something else 

Or is it
typedef map<int,int> MY_MAP; 
MY_MAP my_Map;

3. Insert data
(1) my_Map [1]     =     1;
(2) my_Map. Insert (map < Int, int > : : value_type (2, 2));
(3) my_Map. Insert (pair < Int, int > (3, 3));
(4) my_Map. Insert (make_pair < String, int > (4));

4. Find and modify data
(1)

int i = my_Map[1]; 
    my_Map[1] = i;

(2)
MY_MAP::iterator my_Itr; 
    my_Itr.find(2);
    int j = my_Itr->second;
    my_Itr->second = j;

Note:
A. The key itself cannot be modified unless deleted.
B. Whether the key store exists or not, such as my_Map[1]     =     I; , will perform an assignment.
 
Delete data
(1) my_Map. Erase (my_Itr);
(2) my_Map. Erase (3);

 
6. Traverse the data

for(my_Itr=my_Map.begin();my_Itr!=my_Map.end();++my_Itr){}

7. Other methods
My_map.size () : returns the number of elements
My_map.empty () : determines if it is empty
My_map.clear () : clears all elements

Second, embedded application method

1. Examples are as follows:

map<int,map<int,int> >multiMap; //For such a map nested definition, & NBSP; & have spent & have spent < br / >
map<int, int> temp;    //Define a map<Int, string> Variable, which is defined and inserted into multimap&somalia; & have spent & have spent < br / >
temp[9] = 9;    
temp[10] = 10;   
multiMap[10] = temp;   
multiMap[10][11]=11;    
multiMap[5][30]=30;   
map<int,map<int,int> >::iterator multitr;  //Here's how to traverse a book multiMap  & have spent & have spent < br / > map<int,int>::iterator intertr;   
for(multitr=multiMap.begin();multitr!=multiMap.end();multitr++)   
{  
    for(intertr= multitr ->second.begin(); intertr != multitr ->second.end(); intertr ++)   
        cout<< multitr ->first<<" "<<intertr->first<<" ("<<intertr -> second <<")"<<endl;   
}

2. You can also:

map<int,map<int,int>* >multiMap;  
map<int, int>* temp = new map<int, int>; 
multiMap[10]=temp;

So dynamic new memory, remember delete, otherwise there will be memory leak, delete as follows:

map<int, int>* temp1;  
for(multitr=multiMap.begin();multitr!=multiMap.end();multitr++)   
{  
    temp1 = multitr ->second; 
        delete  temp1; 
        temp1 = NULL; 
}

Hope that the article described in the C++ programming to help you.


Related articles: