map 键-值对的集合,可理解为关联数组。
#include<iostream>
#include<map>
using namespace std;
int main(){
map<string, int> word_cnt;
string word;
/*利用数组下标插入
while(cin >> word){
++word_cnt[word];
}
*/
/*利用insert插入*/
while(cin >> word){
pair<map<string, int>::iterator, int> ret = word_cnt.insert(make_pair(word, 1));
if(!ret.second)
++ret.first->second;
}
/*erase删除键为June的元素*/
word_cnt.erase("June");
/*迭代遍历*/
map<string, int>::const_iterator it = word_cnt.begin();
while(it != word_cnt.end()){
cout << it->first << " occurs "
<< it->second << " times" << endl;
++it;
}
/*测试数据:June July the on the table the July book*/
/*查找 find count*/
map<string, int>::iterator u = word_cnt.find("the");
//find返回迭代器,若不存在则返回指向末端的迭代器
if(u != word_cnt.end()){
cout << u->first << " occurs "
<< u->second << " times" << endl;
}
int cnt = word_cnt.count("July");
//count的返回值是0(容器中不存在)或1(容器中存在),因为map是一个键对应一个值
cout << cnt << endl;
}
multimap 一个键可对应多个值,不能使用下标操作。
#include<iostream>
#include<map>
using namespace std;
int main(){
multimap<string, string> author;
/*用insert添加元素*/
author.insert(make_pair(string("Happy"), string("Hello")));
author.insert(make_pair(string("June"), string("July")));
author.insert(make_pair(string("Happy"), string("Hi")));
author.insert(make_pair(string("Happy"), string("Good")));
/*count(k)返回容器中有k键的元素个数*/
multimap<string, string>::size_type cnt = author.count("Happy");
cout << cnt << endl;
/*find(k)函数返回迭代器*/
multimap<string, string>::iterator c = author.find("Happy");
typedef multimap<string, string>::size_type sz_type;
for(sz_type i = 0; i != cnt; ++i, ++c)
cout << c->second << " ";
/*lower_bound(k)返回不小于k的迭代器,lower_bound(k)返回大于k的迭代器。*/
cout << endl << author.lower_bound("Happy")->second << " "
<< author.upper_bound("Happy")->second << endl;
/*equal_range(k)返回存在k键的元素范围的pair类型(左闭右开区间)*/
typedef multimap<string, string>::iterator authors;
pair<authors, authors> k = author.equal_range("Happy");
cout << k.first->second << " "
<< k.second->second << endl;
}