map的常见用法

map的常见用法,第1张

概述map的常见用法 map 是什么? map是一组键值对的组合,通俗理解类似一种特殊的数组,a[key]=val,只不过数组元素的下标是任意一种类型,而且数组的元素的值也是任意一种类型。有点类似python中的字典。通过"键"来取值,类似生活中的字典,已知索引,来查看对应的信息。(个人理解,其实不准确,内部并不是数组实现的,而是红黑树) map的定义 map<typename1,typename2> map的常见用法 map 是什么?

map是一组键值对的组合,通俗理解类似一种特殊的数组,a[key]=val,只不过数组元素的下标是任意一种类型,而且数组的元素的值也是任意一种类型。有点类似python中的字典。通过"键"来取值,类似生活中的字典,已知索引,来查看对应的信息。(个人理解,其实不准确,内部并不是数组实现的,而是红黑树)

map的定义
map<typename1,typename2> mp;

如果是字符串到其他类型的映射应该使用string

map(string,int) mp;

map的值也可以是stl容器

map(set<int>,string) mp;
map容器内部的访问方式 通过下标来访问
# include <iostream># include <map>using namespace std;int main(voID){    map<char,int> mp;    mp['c']=10;    mp['c']=20;//10被覆盖    cout<<mp['c']<<endl;    return 0;}
通过迭代器来访问

map的迭代器和其他集合的迭代器不同,其具有两种类型分别是typename1,typename2。
通过迭代器it要分别访问集合元素的键和值。
it->first访问键,it->second访问值

# include <iostream># include <map>using namespace std;int main(voID){    map<char,int> mp;    mp['a']=10;    mp['b']=20;    mp['c']=30;    for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)    {        cout<<it->first<<" "<<it->second<<endl;    }    return 0;}

map会以键从小到大自动排序,就是通过‘a‘,‘b‘,‘c‘的顺序来排这三个键值对,这是由于集合内部是通过红黑树来实现的,在建立映射的时候会自动实现从小到大的排序。

map中常见函数 find()

find(key)返回键为key的映射的迭代器,时间复杂度为O(logN),N为map重映射的数量。

# include <iostream># include <map>using namespace std;int main(voID){    map<char,int> mp;    mp['a']=10;    mp['b']=20;    mp['c']=30;    map<char,int>::iterator it=mp.find('a');    cout<<it->first<<' '<<it->second<<endl;    return 0;}
erase() 删除单个元素
# include <iostream># include <map>using namespace std;int main(voID){    map<char,int>::iterator it=mp.find('a');    mp.erase(it);//删除a 10    for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)    {        cout<<it->first<<" "<<it->second<<endl;    }    return 0;}
删除多个元素
# include <iostream># include <map>using namespace std;int main(voID){    map<char,int>::iterator it=mp.find('a');    mp.erase(it,mp.end());//删除it之后的所有映射    for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)    {        cout<<it->first<<" "<<it->second<<endl;    }    return 0;}
size()

获取map中映射的对数

# include <iostream># include <map>using namespace std;int main(voID){    map<char,int> mp;    mp['a']=10;    mp['b']=20;    mp['c']=30;    cout<<mp.size()<<endl;    return 0;}
清空map中的所有元素
# include <iostream># include <map>using namespace std;int main(voID){    map<char,int> mp;    mp['a']=10;    mp['b']=20;    mp['c']=30;    mp.clear();//清空map    cout<<mp.size()<<endl;//0    return 0;}
总结 用途 建立字符串和整数之间的映射 判断数据是否存在 字符串和字符串的映射 总结

以上是内存溢出为你收集整理的map的常见用法全部内容,希望文章能够帮你解决map的常见用法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1191789.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存