C ++, maps usage

All elements of map types are pair type, pair type Guming Si Yee is the type exist in pairs. Such pair <string, string> StudentTom ( "StudentID", "StudentName"), defines a paired Student present a first value of a student number, the second value is the name of the student. The first has been called the key, the second is called value, there are two pairs. This definition is not limited and string type, other types may be used. map type is equivalent to a series of pair types of data.

map type definition: map <string, string> StudentList;

初始化:             StudentList. insert ( map<string,string>::value_type("001","Brown"));

The most commonly used operating functions:

begin () returns a pointer to the iterator map head
end () returns a pointer to the end of the map iterator

 

The following is the use of map types to complete the Student ID binding name, complete insert, search, traverse, delete the program

1  / * using a map number to complete by binding type name, the insertion is completed, look, traversing, deleting * / 
2 #include <the iostream>
 . 3 #include < String >
 . 4 #include <map>
 . 5  the using  namespace STD;
 . 6  
. 7  void map_insert (Map < String , String > * mapStudent, String ID, String name)
 . 8  { 
 . 9      mapStudent-> INSERT (Map < String , String > :: the value_type (ID, name));
 10  };
 . 11  int main ()
 12 is  {
13     map<string, string>mapS;
14     //插入同学
15     map_insert(&mapS,"001","Brown");
16     map_insert(&mapS, "002", "Cony");
17     map_insert(&mapS, "003", "Tom");
18 
19     //查找同学
20     map<string, string>Iterator ITER ::;
 21 is      ITER = mapS.find ( " 003 " );
 22 is      IF (! = ITER mapS.end ())
 23 is      {
 24          COUT << " find the student " ;
 25          COUT << iter-> SECOND < <endl << endl;
 26 is      }
 27      the else 
28      {
 29          COUT << " not found the student " << endl;
 30      }
 31 is  
32      // view all students (traversing) 
33 is      for(ITER mapS.begin = ();! = mapS.end ITER (); ++ ITER )
 34 is      {
 35          COUT iter- << endl <<> << First iter-> SECOND << endl;
 36      }
 37 [  
38 is      // Delete a student 
39      ITER = mapS.find ( " 003 " );
 40      IF (! = ITER mapS.end ())
 41 is      {
 42 is          COUT << endl << " delete student is " ;
 43 is          COUT << iter-> SECOND << endl;
 44 is          mapS.erase (ITER);
45      }
 46      else
47     {
48         cout << "没找到该同学";
49 
50     }
51     for (iter = mapS.begin(); iter != mapS.end(); iter++)
52     {
53         cout << iter->first << iter ->second<< endl;
54     }
55 
56     getchar();
57     return 0; 
58     
59         
60 }

 

Guess you like

Origin www.cnblogs.com/wuhongjian/p/11519980.html