C ++ getting started -- map of the standard template library

Source: Internet
Author: User

C ++ getting started -- map of the standard template library

Map is an associated container of STL, which provides one-to-one (the first can be called a keyword, each keyword can only appear once in map, and the second can be called the value of this keyword) because of this feature, it is possible to provide a quick channel for programming when we process one-to-one data. Here, we will briefly talk about the organization of map internal data. Within the map, we will build a red/black tree (a non-strictly balanced binary tree), which has the ability to automatically sort data, therefore, all the data in the map is ordered, and we will see the benefits of ordering later.

 

So what is one-to-one data ing? For example, in a class, each student's student ID has a one-to-one ing relationship with his name. This model may be easily described using map. Obviously, the student ID is described using int, the name is described in a string.

 

Before using map, you must include the corresponding header file. map belongs to the std naming domain. Therefore, you must use the naming restrictions:

# Include

Using std: map; // using namespace std;

 

 

1) map constructor map provides a total of six constructor functions, which involve the memory distributor. I will skip this article. Below we will be exposed to some map constructor methods, we usually construct a map using the following method:

 

 

map
 
   mapStudent;
 

2) data insertion

 

After constructing the map container, We can insert data into it. Here are three data insertion methods:

A) insert pair data using the insert function:

 

# Include
 
  
# Include
  // Map # include
   
    
// String # include
    
     
// Pairusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly insert all contained items // use the insert function to insert the pair data int main (int argc, char * argv []) {map
     
      
MapStudent; // insert pair data using the insert function mapStudent. insert (pair
      
        (1, student_one); mapStudent. insert (pair
       
         (2, student_two); mapStudent. insert (pair
        
          (3, student_three); // uses the iterator to traverse the map content map
         
           : Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
          
            First <
           
             Second <
            
             

The running result is as follows:

 

B) Use the insert function to insert value_type data:

 

# Include
              
               
# Include
               // Map pair # include
                
                 
// String # include
                 
                  
// Pairusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly insert all data that contain/// use the insert function to insert value_type data int main (int argc, char * argv []) {map
                  
                   
MapStudent; // insert value_type data using the insert function mapStudent. insert (map
                   
                     : Value_type (1, student_one); mapStudent. insert (map
                    
                      : Value_type (2, student_two); mapStudent. insert (map
                     
                       : Value_type (3, student_three); // uses the iterator to traverse the map content
                      
                        : Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                       
                         First <
                        
                          Second <
                         
                          C) insert data using Arrays:
                          

 

 

# Include
                           
                            
# Include
                            // Map pair # include
                             
                              
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all the data. // insert data in an array in int main (int argc, char * argv []) {map
                              
                               
MapStudent; // insert data in an array. mapStudent [0] = student_one; mapStudent [2] = student_two; mapStudent [3] = student_three; // use the iterator to traverse the map content map
                               
                                
: Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                
                                  First <
                                 
                                   Second <
                                  
                                    The running result is as follows:
                                   

 

Although data can be inserted in the preceding three methods, they are different. The first and second methods are the same in terms of performance. Using the insert function to insert data involves the concept of uniqueness of the Set in data insertion, that is, if a keyword already exists in the map, the insert operation cannot insert data successfully, but it can be used as an array. It can overwrite the value corresponding to the previous keyword.

 

So how do we know whether the insert statement is successfully inserted? We can use pair to determine whether the insert is successful:

 

pair< map
                                    
                                     ::iterator, bool > insert_pair;insert_pair = mapStudent.insert( map
                                     
                                      ::value_type(1, student_one) );
                                     
                                    

 

 

The second pair variable is used to determine whether the insert is successful. The first variable returns a map iterator. If the insert is successful, the value of insert_pair.second is true; otherwise, the value of false.

 

The complete test code is as follows:

 

# Include
                                    
                                     
# Include
                                     // Map pair # include
                                      
                                       
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them // test whether the insertion is successful int main (int argc, char * argv []) {map
                                       
                                        
MapStudent; pair
                                        
                                         
: Iterator, bool> insert_pair; // insert data insert_pair = mapStudent. insert (pair
                                         
                                           (1, student_one); if (insert_pair.second = true) // The insertion is successful {cout <Insert Successfully <endl ;} else {cout <Insert Failure <endl;} // Insert data insert_pair = mapStudent. insert (pair
                                          
                                            (1, student_two); if (insert_pair.second = true) // Insert success {cout <Insert Successfully <endl ;} else {cout <Insert Failure <endl;} cout <----------------------; // uses the iterator to traverse the map content map
                                           
                                             : Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                            
                                              First <
                                             
                                               Second <
                                              
                                                The running result is as follows:
                                               

 

 

The following example shows how to assign values to the test array to overwrite data:

 

# Include
                                                
                                                 
# Include
                                                 // Map pair # include
                                                  
                                                   
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly assign values to all contained arrays. Data overwrite int main (int argc, char * argv []) {map
                                                   
                                                    
MapStudent; mapStudent [1] = student_one; mapStudent [1] = student_two; // This is also 1 mapStudent [2] = student_three; cout <------------------------; // use the iterator to traverse the map content map
                                                    
                                                     
: Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                                     
                                                       First <
                                                      
                                                        Second <
                                                       
                                                         The running result is as follows:
                                                        

 

 

3) map size

How do we know how much data has been inserted into the map? The size function can be used as follows:

 

int nSize = mapStudent.size();

4) Data Traversal

 

A) through the forward iterator, this method is used in the above example program.


B) through the reverse iterator:

 

# Include
                                                         
                                                          
# Include
                                                          // Map pair # include
                                                           
                                                            
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them // use the reverse iterator to traverse the map content int main (int argc, char * argv []) {map
                                                            
                                                             
MapStudent; // insert pair data using the insert function mapStudent. insert (pair
                                                             
                                                              
(1, student_one); mapStudent. insert (pair
                                                              
                                                                (2, student_two); mapStudent. insert (pair
                                                               
                                                                 (3, student_three); // cout <----------------------; // uses the reverse iterator to traverse the map content map
                                                                
                                                                  : Reverse_iterator iter; for (iter = mapStudent. rbegin (); iter! = MapStudent. rend (); iter ++) {cout <
                                                                 
                                                                   First <
                                                                  
                                                                    Second <
                                                                   
                                                                    

 

 

The running result is as follows:

 

C) array:

 

# Include
                                                                     
                                                                      
# Include
                                                                      // Map pair # include
                                                                       
                                                                        
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them // use an array to traverse the map content int main (int argc, char * argv []) {map
                                                                        
                                                                         
MapStudent; // insert pair data using the insert function mapStudent. insert (pair
                                                                         
                                                                          
(1, student_one); mapStudent. insert (pair
                                                                          
                                                                            (2, student_two); mapStudent. insert (pair
                                                                           
                                                                             (3, student_three); // cout <----------------------; // use an array to traverse the map content int n = mapStudent. size (); for (int I = 1; I <= n; I ++) // {cout <I <mapStudent [I] <
                                                                            
                                                                              5) data search
                                                                             

 

You can use the find function to locate the data occurrence location. It returns an iterator. When the data appears, it returns the iterator where the data is located. If there is no data to be searched in the map, the iterator it returns is equal to the iterator returned by the end function. The sample code is as follows:

 

# Include
                                                                              
                                                                               
# Include
                                                                               // Map pair # include
                                                                                
                                                                                 
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them // use the find function to locate the data occurrence location int main (int argc, char * argv []) {map
                                                                                 
                                                                                  
MapStudent; // insert pair data using the insert function mapStudent. insert (pair
                                                                                  
                                                                                   
(1, student_one); mapStudent. insert (pair
                                                                                   
                                                                                     (2, student_two); mapStudent. insert (pair
                                                                                    
                                                                                      (3, student_three); map
                                                                                     
                                                                                       : Iterator iter; iter = mapStudent. find (1); // search for 1 content if (iter! = MapStudent. end () // locate {cout <Find, the value is: <iter-> second <endl ;} else {cout <Do not Find <endl;} return 0 ;}
                                                                                     
                                                                                    
                                                                                   
                                                                                  
                                                                                 
                                                                                
                                                                              

The running result is as follows:

 

 

 

6) clear and empty the data in the map can be cleared by using the clear () function to determine whether there is data in the map. The empty () function can be used, if it returns true, it indicates that the map is empty.

 

 

 

7) the erase function is used to delete data. There are three overloaded functions. The following describes their usage in detail in the example:

 

 

# Include
                                                                              
                                                                               
# Include
                                                                               // Map pair # include
                                                                                
                                                                                 
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly delete all contained data. // int main (int argc, char * argv []) {map
                                                                                 
                                                                                  
MapStudent; // insert pair data using the insert function mapStudent. insert (pair
                                                                                  
                                                                                   
(0, student_zero); mapStudent. insert (pair
                                                                                   
                                                                                     (1, student_one); mapStudent. insert (pair
                                                                                    
                                                                                      (2, student_two); mapStudent. insert (pair
                                                                                     
                                                                                       (3, student_three); mapStudent. insert (pair
                                                                                      
                                                                                        (4, student_four); // if you want to delete 1, use the iterator to delete the map
                                                                                       
                                                                                         : Iterator iter; iter = mapStudent. find (1); // first find 1mapStudent. erase (iter); cout <after erase 1:; // uses the iterator to traverse the map content for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                                                                        
                                                                                          First <
                                                                                         
                                                                                           Second <
                                                                                          
                                                                                            First <
                                                                                           
                                                                                             Second <
                                                                                            
                                                                                              First <
                                                                                             
                                                                                               Second <
                                                                                              
                                                                                                The running result is as follows:
                                                                                               

 

 

 

8) sorting

Here we will talk about a relatively advanced usage: Sorting is a problem. By default, STL uses smaller numbers for sorting. The above Code does not have any problems in sorting, because the above keyword is int type, it supports less than number calculation. In some special cases, for example, if the keyword is a struct, a problem occurs when sorting is involved because it is not less than number operation, insert and other functions cannot pass during compilation. The test code is as follows:

 

# Include
                                                                                                
                                                                                                 
# Include
                                                                                                 // Map pair # include
                                                                                                  
                                                                                                   
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them with typedef struct tagStudentInfo {int nID; string strName;} StudentInfo, * PStudentInfo; // student information // data deletion int main (int argc, char * argv []) {// map the score map with student information
                                                                                                   
                                                                                                    
MapStudent; StudentInfo studentInfo; studentInfo. nID = 1; studentInfo. strName = student_one; mapStudent. insert (pair
                                                                                                    
                                                                                                     
(StudentInfo, 90); studentInfo. nID = 2; studentInfo. strName = student_two; mapStudent. insert (pair
                                                                                                     
                                                                                                       (StudentInfo, 80); map
                                                                                                      
                                                                                                        : Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                                                                                       
                                                                                                         First. nID <
                                                                                                        
                                                                                                          First. strName <
                                                                                                         
                                                                                                           Second <
                                                                                                          
                                                                                                           

 

The above programs cannot be compiled.

Solution: Reload the minor signs. Example:

 

# Include
                                                                                                            
                                                                                                             
# Include
                                                                                                             // Map pair # include
                                                                                                              
                                                                                                               
// Stringusing std: endl; using std: cin; using std: cout; using std: map; using std: string; using std: pair; // using namespace std; // or directly include all of them with typedef struct tagStudentInfo {int nID; string strName; bool operator <(tagStudentInfo const & temp) const {// This function specifies the sorting policy, which is sorted by nID. if nID is equal, it is sorted by strName if (nID <temp. nID) return true; if (nID = temp. nID) return strName. compare (temp. strName); return false ;}} StudentInfo, * PStudentInfo; // student information // data deletion int main (int argc, char * argv []) {// map the score map with the student information
                                                                                                               
                                                                                                                
MapStudent; StudentInfo studentInfo; studentInfo. nID = 1; studentInfo. strName = student_one; mapStudent. insert (pair
                                                                                                                
                                                                                                                 
(StudentInfo, 90); studentInfo. nID = 2; studentInfo. strName = student_two; mapStudent. insert (pair
                                                                                                                 
                                                                                                                   (StudentInfo, 80); map
                                                                                                                  
                                                                                                                    : Iterator iter; for (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++) {cout <
                                                                                                                   
                                                                                                                     First. nID <
                                                                                                                    
                                                                                                                      First. strName <
                                                                                                                     
                                                                                                                       Second <
                                                                                                                      
                                                                                                                       

 

The running result is shown as follows:

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.