map

来源:互联网 发布:windows介质创建工具 编辑:程序博客网 时间:2024/05/15 16:42

Before talking about map, we need to know pair. The class pair treats two values as a single unit.  This class is used in several places within the C++ standard library.  In particular, the container classes map, multimap, unordered_map, and unordered_multimap use pairs to manage their elements, which are key/value pairs. The structure pair is defined in <utility> and provides the operations listed below. In principle, you can create, copy/assign/swap, and compare a pair<>. In addition, there are type definitions for first_type and second_type, representing the types of the first and second values.

To process the values of the pair direct access to the corresponding members is provided. In fact, the type is declared as struct instead of class so that all members are public:

template  <typename  T1,  typename  T2>struct  pair  {    // member    T1  first;    T2  second;    ...};

Some basic operations for map in stl.

#include<iostream>#include<map>using namespace std;int main(){    map<int, string> mymap;    pair<int, string> s1(1, "Tim");    pair<int, string> s2(2, "Sam");    pair<int, string> s3(6, "David");    pair<int, string> s4(5, "James");    pair<int, string> s5(1, "Tim");    mymap.insert(s1);    mymap.insert(s2);    mymap.insert(s3);    mymap.insert(s4);    mymap.insert(s5);    map<int, string>::iterator itr = mymap.begin();    while(itr!=mymap.end()){        cout << (*itr).first << "\t" << (*itr).second << endl;        itr++;    }    return 0;}

One more example.

0 0