熟练掌握STL常用函数 map函数(基础)

熟练掌握STL常用函数 map函数(基础) map函数常用用法1.前提头文件#includemap2.特点int 按从小到大键唯一不能重复重复会覆盖mp[xiaoming] 85; mp[xiaoming] 100; // 会覆盖结果是 100mapint ,int mpstring 按字典序eg:mp[“xiaoming”]85; mp[“xiaohong”]85; //输入 //自动型 anto 自适应类型 for(anto it:mp)//将容器map从头到尾 都遍历一遍 { cout it.first ‘ ’ it.second endl; }经过遍历之后xiaohong 85 xiaoming 65 //输出根据第一个数据红字 int 按照字典排序3.定义mapint ,int mp;map数据类型数据类型 命名map键类型, 值类型 名字; mapstring, int mp; // 姓名→分数 mapint, int mp; // 学号→分数4.存储mp[1000000001]82;mp[1000000002]80;5.访问mp[1000000001]82;mp[1000000002]80;cout mp[1000000001] endl;6.查询在你不知道是否存在该数据时 用 findif(mp.find(10000005)!mp.end()) { cout mp[10000005] endl; } else { cout 没有此人信息 endl; } //或者 if(mp.find(10000005)mp.end()) { cout 没有此人信息 endl; } else { cout mp[10000005] endl; }只查一次最快auto it mp.find(key); if (it ! mp.end()) { // 找到了 cout it-second endl; } else { // 没找到 cout 无信息 endl; }count () 快速判断键是否存在比 find 更短if(mp.count(xiaoming)){ cout 存在; }7.遍历//自动型 auto 自适应类型 #includeiostream #includecstdio #includecstring #includemap using namespace std; mapstring,intmp; int main() { mp[xiaoming]85; mp[xiaohong]65; for(auto it:mp)//将容器 map从头到尾 都遍历一遍 { cout it.first it.second endl;//不同于vector等 } return 0; } //迭代器 #includeiostream #includecstdio #includecstring #includemap using namespace std; mapstring,intmp; int main() { mp[xiaoming]85; mp[xiaohong]65; map string,int ::iterator it; //定义mapstring,intmp类型的迭代器 //其中迭代器it就是指指针指向地址 for(itmp.begin() ;it!mp.end() ;it) { cout(*it).first (*it).second endl; } return 0; }auto 引用遍历更快for(auto it : mp) // 加 引用8. 删除mp.erase(xiaoming); // 按 key 删除 mp.erase(it); // 按迭代器删除 mp.clear(); // 清空全部9. 大小 判空mp.size(); // 元素个数 mp.empty(); // 是否为空