C++中的unordered_map

#include <stdio.h>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

void main(){
    unordered_map<string,int> months;
    //插入数据
    cout<<"insert data"<<endl;
    months["january"]=31;
    months["february"] = 28;
    months["march"] = 31;
    months["september"] = 30;

    //直接使用key值访问键值对,如果没有访问到,返回0
    cout<<"september->"<<months["september"]<<endl;
    cout<<"xx->"<<months["xx"]<<endl;

    typedef unordered_map<int,int> mymap;
    mymap mapping;
    mymap::iterator it;
    mapping[2]=110;
    mapping[5]=220;
    const int x=2;const int y=3;//const是一个C语言(ANSI C)的关键字,它限定一个变量不允许被改变,产生静态作用,提高安全性。

    //寻找是否存在键值对
    //方法一:
    cout<<"find data where key=2"<<endl;
    if( mapping.find(x)!=mapping.end() ){//找到key值为2的键值对
        cout<<"get data where key=2! and data="<<mapping[x]<<endl;
    }
    cout<<"find data where key=3"<<endl;
    if( mapping.find(y)!=mapping.end() ){//找到key值为3的键值对
        cout<<"get data where key=3!"<<endl;
    }
    //方法二:
    it=mapping.find(x);
    printf("find data where key=2 ?  %d\n",(it==mapping.end()));
    it=mapping.find(y);
    printf("find data where key=3 ?  %d\n",(it==mapping.end()));

    //遍历hash table
    for( mymap::iterator iter=mapping.begin();iter!=mapping.end();iter++ ){
        cout<<"key="<<iter->first<<" and value="<<iter->second<<endl;
    }
//c++11中更方便地遍历
for auto x : mapping
cout << x.first << " " << second << endl;
 system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值