Map是一种关联容器,特点是增删节点对迭代影响很小。Map由建(First)和值(second)构成。其键是无法更改的(const)
Map的声明
map<string, int> strMap; 一个键为string,值为int的map
Map的添加元素(注意是类似栈一样的,先添加的元素在最后面,即如果iter.begin()->first = david)
strMap[string("jjhou")] = 1;
strMap[string("jerry")] = 2;
strMap[string("jason")] = 3;
strMap[string("jimmy")] = 4;
pair<string, int> value(string("david"), 5);
strMap.insert(value);
Map和set想要得到其中的某个元素都必须用其专有的引用来迭代直,到得到其想要的元素但是无法修改,因为map的关键字元素和set的关键字元素都是const的
专有迭代器大概是这种感觉:
map<string, int>::iterator strmap_iter = strMap.begin();
for (; strmap_iter != strMap.end(); strmap_iter++)
{
cout << strmap_iter->first << ' ' << strmap_iter->second << endl;
}
Map的查找元素:(只能通过迭代器相等来查找)
map<string, int>::iterator iter1;
//面对关联式容器,应该使用其所提供的find函数来搜索元素,会比使用STL算法find()更有效率。因为STL算法find()只是循环搜索。
iter1 = strMap.find(string("mchen"));
if (iter1 == strMap.end())
cout << "mchen no fount" << endl;
cout << endl;
iter1 = strMap.find(string("jerry"));
if (iter1 != strMap.end())
cout << "jerry fount" << endl;
cout << endl;
Map修改元素:(只能修改实际值,即second)
iter1->second = 9; //可以通过map迭代器修改“value”(not key)
Map删除元素:(earse,即可删除second,又可同时删除first和second)
map<string, int>::iterator iter1;
iter1 = strMap.find(string("mchen"));
strMap.erase(iter1);//删除一个条目
strMap.erase(string("jason"));//根据键值删除
Map通过下标寻找元素:(map.at()或者map[],括号里的元素都是map的键值)
cout<<strMap[string("jjhou")] << endl;
Map.find()返回一个迭代器,如果find不到元素的话会迭代到Map.end
map<string, int> strMap;
strMap[string("jerry")] = 2;
map<string, int>::iterator ax = strMap.find(string("jerry"));
cout<<ax->second << endl;
Map.count()的用法:传入一个键值参数,返回出现的次数
map<string, int> strMap;
strMap[string("jerry")] = 2;
cout<<ax->count(string("jerry")) << endl;
本文改自:https://blog.csdn.net/seanyxie/article/details/5804974