C++中怎么使用map标准模板库,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
一:介绍
map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。
命名空间为std,所属头文件<map> 注意:不是<map.h>
二:常用操作
容量:
修改:
a.插入数据:map.insert()
b.清空map元素:map.clear()
c.删除指定元素:map.erase(it)
迭代器:
三:存储
map<int, string> map1;
//方法1:
map1.insert(pair<int, string>(2, "beijing"));
//方法2:
map1[4] = "changping";
//方法3:
map1.insert(map<int, string>::value_type(1, "huilongguan"));
//方法4:
map1.insert(make_pair<int, string>(3, "xierqi"));
四:遍历
for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
{
cout << it->first << ":" << it->second << endl;
}
五:查找
string value1 = map1[2];
if (value1.empty())
{
cout << "not found" << endl;
}
//方法2
map<int, string>::iterator it = map1.find(2);
if (it == map1.end())
{
cout << "not found" << endl;
}
else
{
cout << it->first << ":" << it->second << endl;
}
六:修改
//修改数据
map1[2] = "tianjin";
七:删除
//方法1
map1.erase(1);
//方法2
map<int, string>::iterator it1 = map1.find(2);
map1.erase(it1);
看完上述内容,你们掌握C++中怎么使用map标准模板库的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!