map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。map关联容器也是采用红黑树来实现的,插入元素的键值不允许重复,比较函数只针对元素的键值进行比较,
元素的各项数据可以通过键值搜索出来,map里面的元素都是有序的。
键值 映照数据
Jack | 100.0 |
Bomi | 75.5 |
Kate | 90.5 |
注意 : map是要有两个数据类型的,一个是键值的数据类型,一个是映照数据的
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,double> m;
//插入元素,按键值从小到大放入红黑树中
m["Jack"] = 100.0;
m["Bomi"] = 75.5;
m.insert(make_pair("kate",90.5));
for(map<string,double>::iterator it = m.begin(); it != m.end(); it++)//遍历输出
{
cout << (*it).first << " " << (*it).second<<endl; //it->first
}
cout<<m["Bomi"]<<endl;//访问
cout<<m.at("Bomi")<<endl; //访问
return 0;
}
另一种访问方式
for(auto it:m)
{
int x = it.second;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<int,char> m;
m[0] = 'A';
m[1] = 'B';
m.insert(make_pair(2,'C'));
m.insert(make_pair(3,'D'));
map<int,char>::iterator it;
it = m.find(2);
if(it != m.end())
cout << (*it).first << " " << (*it).second << endl;
else
printf("not found it\n");
it = m.find(50);
if(it != m.end())
cout << (*it).first << " " << (*it).second << endl;
else
printf("not found it\n");
return 0;
}