map<string,int>::key_type; //键的类型 const string map<string,int>::mapped_type; //值得类型 Int map<string,int>::value_type; //map所存元素的类型 pair<const string,int>类型
map<string ,int> m; map<string,int> m(m2); map<string,int> m(b,e); map<string,int>::iterator ite = m.begin(); ite->first = "hwl"; //error:key is const set<string> s; set<string> s(s2); set<string> s(b.e);3、map类型的访问
m["hwl"]; //m中没有键值为hwl的添加一个,采用值初始化方式初始化值。有的话访问m的值。
//典型的用法:统计词频
string wrods;
map<string,int> words_count;
while (cin>>words)
{
++words_count[words];
}(2)使用count检查map对象中某键是否存在(0 / 1)int occurs = 0;
if (words_count.count("hwl"))
{
occurs = words_count["hwl"];
}两次查找map中的元素效率低。int occurs = 0;
map<string,int>::iterator ite = words_count.find("hwl");
if (ite != words_count.end())
{
occurs = ite->second;
}4、map对象和set对象添加元素map<string,int>words;
set<string> keys;
//...1
pair<map<string,int>::iterator,bool> re = wrods.insert(map<string,int>::value_type("hwl",1));
pair<map<string,int>::iterator,bool> re = wrods.insert(make_pair("hwl",1));
pair<set<string>::iterator,bool> re = keys.insert("hwl");
//...2
wrods.insert(b,e);
keys.insert(b,e);
//...3
words.insert(ite,value_type);5、map对象删除元素map<string,int> words;
words.erase("hwl"); //返回size_type类型(0 / 1)
words.erase(ite); //返回void,ite所指的元素必须存在
words.erase(b,e); //返回void二、multimap和multiset类型multimap<string,string> authors;
authors.insert(make_pair("hwl","IBNFGMGM"));
authors.insert(make_pair("hwl","IBN123333"));
multimap<string,string>::size_type cnt = authors.erase("hwl");//返回删除的个数
authors.erase(ite);//返回void
authors.erase(b,e);//返回void2、查找元素authors.lower_bound(key); //返回一个迭代器,指向键不小于key的第一个元素 authors.upper_bound(key); //返回一个迭代器,指向键大于key的第一个元素 authors.equal_range(key); //返回一个pair对象第一个元素等价于authors.lower_bound(key),第二个等价于authors.upper_bound(key); pair<authors::iterator,authors::iterator> pos = authors.equal_range(key);
原文:http://blog.csdn.net/h_wlyfw/article/details/19499937