C++中的关联容器multimap/multiset用法
时间:2010-12-29 来源:LaoLiulaoliu
声明
multimap<string, string> authors;
元素的添加
//adds first element with key Barth
authors.insert(make_pair(string(“Barth, John”), string(“Sot-Weed Factor”)));
//ok: adds second element with key Barth
authors.insert(make_pair(string(“Barth, John”), string(“Lost in the Funhouse”)));
元素的删除
string search_item(“Kazuo Ishiguro”);
//erase all elements with this key; returns number of elements removed
multimap<string, string>::size_type cnt=authors.erase(search_item);
查找元素
方法1: find count
//author we’ll look for
string search_item(“Alain de Botton”);
//how many entries are there for this author
typedef multimap<string, string>::size_type sz_type;
sz_type entries=author.count(search_item);
//get iterator to the first entry for this author
multimap<string, string>::iterator iter=author.find(search_item);
//loop through the number of entries there are for this author
for(sz_type cnt=0; cnt<entries; ++cnt, ++iter)
cout<<iter->second<<endl; //print each titile
首先调用count确定某作者所写的书籍数目,然后调用find获得指向第一个该键所关联的元素的迭代器。for循环迭代的次数依赖于count返回的值。在特殊情况下,如果count返回0值,则该循环永不执行。
方法2: lower_bound upper_bound
//definitions of authors and search_item as above
//beg and end denote range of elements for this author
typedef multimap<string, string>::iterator authors_it;
authors_it beg=authors.lower_bound(search_item),
end=authors.upper_bound(search_item);
//loop through the number of entries there are for this author
while(beg!=end){
cout<<beg->second<<endl;//print each title
++beg;
}
在同一个键上调用lower_bound和upper_bound,将产生一个迭代器范围,指示出该键所关联的所有元素。如果该键在容器中存在,则会获得两不同的迭代器:lower_bound返回的迭代器指向该键关联的第一个实例,而upper_bound返回的迭代器则指向最后一个实例的下一位置。如果该键不在multimap中,这两个操作将返回同一个迭代器,指向依据元素的排列顺序该键应该插入的位置。
方法3: equal_range
//definitions of authors and search_item as above
//pos holds iterators that denote range of elements ofr this key
pair<authors_it, authors_it> pos=authors.equal_range(search_item);
//loop through the number of entries there are for this author
while(pos.first!=pos.second){
cout<<pos.first->second<<endl;//print each titile
++pos.first;
}
pair对象的first成员存储lower_bound函数返回的迭代器,而second成员则记录upper_bound函数返回的迭代器。