map 用法详解
来源:互联网 发布:qq影音mac官方下载 编辑:程序博客网 时间:2024/06/07 02:38
和vector一样,map也可以看作一种特殊的数组,vector是不限定长度的数组,map是可以不开中间位置元素空间的数组。
map常见的函数:
m.insert(pair) //插入一对数据m.size() //返回容器中元素的个数m.count(key) //返回key键是否出现过m.find(key) //寻找key键元素,返回到迭代器m.erase(pos) //删除迭代器指向位置的元素m.empty() //判断是否为空m.clear() //清空容器
新建容器对象:
新建一个容器对象和迭代器: map <类型1,类型2> 容器名称;
map <类型1,类型2> ::iterator 迭代器名称;
map元素有两个部分,前面的叫做键,后面的叫做值。
以键值对< a , b >为例:
添加元素的三种方式: m.insert(pair<int,int>(a,b));
m.insert(map<int,int>::value_type(a,b));
m[a]=b;
和vector一样,访问元素尽量使用迭代器:
可以用for循环遍历容器,或者用find函数查找相应键的值: it=find(a);
迭代器指向键a所对应的元素 it->first
指向迭代器所指向元素的键 it->second
指向迭代器所指向元素的值
也可以用最值接的方法: m[a];
来求出键a对应的值
下面来个样例:
#include"stdio.h"#include"iostream"#include"map"using namespace std;int main(){//初始化 map <int,int> mp; map <int,int> ::iterator it;//三种插入方式 mp.insert(pair<int,int>(3,8)); mp.insert(pair<int,int>(11,21)); mp.insert(pair<int,int>(12,22)); mp.insert(pair<int,int>(13,23)); mp.insert(pair<int,int>(14,24)); mp.insert(pair<int,int>(15,25)); mp.insert(map<int,int>::value_type(4,9)); mp[5]=10;//判断键位5是否出现过 printf("%d\n",mp.count(5)); printf("容器的元素分别为:\n");//遍历取值方式 for(it=mp.begin(); it!=mp.end(); it++) { printf("%d %d\n",it->first,it->second); }//通过函数查值 printf("寻找下标为3的元素:"); int f=3; it=mp.find(f); //找不到迭代器会返回end指针 if(it==mp.end()) printf("NO\n"); else printf("%d %d\n",it->first,it->second);//直接用下标查值 printf("直接下标查找的结果:"); printf("%d\n",mp[3]);//删除区间值 int minn=5; int maxn=13; printf("删除键为%d到%d的所有元素\n\n",minn,maxn); map <int,int> ::iterator itfrom=mp.lower_bound(minn); map <int,int> ::iterator itto=mp.upper_bound(maxn); if(itfrom!=mp.end()) printf("第一个被删的是:\n%d %d\n",itfrom->first,itfrom->second); if(itto!=mp.end()) printf("最后一个被删的后一个数是:\n%d %d\n",itto->first,itto->second); mp.erase(itfrom,itto); printf("删除后的容器:\n"); for(it=mp.begin(); it!=mp.end(); it++) { printf("%d %d\n",it->first,it->second); }}
0 0
- map-STL用法详解
- map用法详解
- map - STL 用法详解
- STL MAP用法详解
- STL map用法详解
- map用法详解
- STL MAP用法详解
- STL map 用法详解
- map用法详解
- std map用法详解
- Map的用法详解
- Map的用法详解
- STL map用法详解
- STL MAP用法详解
- STL map用法详解
- map用法详解
- STL--map用法详解
- STL MAP用法详解
- php5中的clone 浅拷贝 深拷贝
- First Missing Positive
- poj 3061 尺取法
- 驯裁轮菊干站沉胖屑倏轿腋烈呕夹
- #笔记#圣思园 JavaWeb 第65讲——jQuery,选择器
- map 用法详解
- hdu 1575 try a 矩阵快速幂
- BadParcelableException:Parcelable protocol requires a Parcelable 错误
- 九度OJ 题目1031:xxx定律
- session与cookie的区别
- 图的深度遍历
- iOS 使用category将复杂的类拆分
- CodeForces #Pi D.One-Dimensional Battle Ships
- 九大排序算法总结