map

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值