STL map

概述

map映照容器是一种实现了平衡二叉树的数据结构,Map中每个元素都是一个键值对<key,value>,且key值是不能重复的,即每个元素的key值都是唯一的。Map容器可以按key检索

map容器的定义:

map<类型1,类型2>对象名;如:map<string,float> m;其中,类型1是key的类型,类型2是value的类型。

                                                    map<int,vector<int> >m;

查找:

map内的元素能以数组的方式进行访问

例子:

#include<iostream>
#include<map>
using namespace std;
int main(){

    map<int,string>a;
    a[2]="dwd";
    a[5]="dff";
    a[6]="asf";
    a[8]="21";
    a[10]="345";
    a.erase(2);
    for(int i=1;i<=a.size();i++)
        cout<<a[i]<<endl;

    cout<<a.find(5)->first<<a.find(5)->second;

    return 0;
}

二分查找:

.lower_bound(x);           返回第一个大于等于x的数的地址(迭代器)           可用.first和.second访问其key值和value值

.upper_bound(x);           返回第一个大于x的数的地址(迭代器)

如果所有元素都小于x,则返回最后一个下标+1的位置

遍历:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, int> _map;
    _map[0] = 1;
    _map[1] = 2;
    _map[10] = 10;

    map<int, int>::iterator iter;
    iter = _map.begin();
    while(iter != _map.end()) {
        cout << iter->first << " : " << iter->second << endl;
        iter++;
    }

    // 也可以使用for循环遍历
    /*
    for(iter = _map.begin(); iter != _map.end(); iter++) {
        cout << iter->first << " : " << iter->second << endl;
    }
    */
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值