Map是STL的一个关联容器,它提供一对一(其中第一个能够称为关键字,每一个关键字只能在map中出现一次,第二个称为该关键字的值)的数据 处理能力。c++
#include <map>
map<string,int>m;
这是定义了一个以string为关键字,以int为值的map函数
map<string,int>m; m["Bob"]=101; m["Alice"]=102; m["Eric"]=103;
m.insert(pair<string,int>("Lee",104));
m.insert(map<string,int>::value_type("Karen",105));
定义一个迭代指针iter,使其指向map,实现对map的遍历。spa
#include<bits/stdc++.h> using namespace std; int main() { map<string,int>m; m["Bob"]=101; m["Alice"]=102; m["Eric"]=103; map<string,int>::iterator iter; for(iter=m.begin(); iter!=m.end(); iter++) cout<<iter->first <<"->"<<iter->second<<endl; }
输出为:指针
Alice->102 Bob->101 Eric->103
能够看到map自动在内部以关键字为准,按字典序排序,而不是根据输入的顺序;code
须要注意的是 当我进行实验的时候 我发现这样一个现象:blog
#include<bits/stdc++.h> using namespace std; int main() { map<string,int>m; m["Bob"]=101; m["Alice"]=102; m["Eric"]=103; map<string,int>::iterator iter; for(iter=m.begin(); iter!=m.end(); iter++) cout<<iter->first <<"->"<<iter->second<<endl; if(m["AAA"]==0) cout<<"NO"<<endl; for(iter=m.begin(); iter!=m.end(); iter++) cout<<iter->first <<"->"<<iter->second<<endl; }
当询问一个map中不存在的数的时候,返回的值应该是0,不过当你再次遍历的时候,就会发现map中已经多了一个键值对,只不过值是0:排序
Alice->102 Bob->101 Eric->103 NO AAA->0 Alice->102 Bob->101 Eric->103
在作题时必定要好好注意。get
cout<<m.find("Bob")->second<<endl;
若是按关键字搜索,搜不到的话会输出乱码string
map<string,int>::iterator iter1; iter1 = m.find(string("Bob")); if(iter1 != m.end()) cout<<iter1->first <<"->"<<iter1->second<<endl; else cout<<"no fount"<<endl;
定义一个指针,指向map,若是没有的话会返回m.end()it
m.erase(iter1);
一样的是指针的操做
m.erase(string("AAA"));
或者是根据关键字删除