分类: C/C++
2008-11-28 10:12:39
声明
multimap
元素的添加
//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
查找元素
方法1: find count
//author we’ll look for
string search_item(“Alain de Botton”);
//how many entries are there for this author
typedef multimap
sz_type entries=author.count(search_item);
//get iterator to the first entry for this author
multimap
//loop through the number of entries there are for this author
for(sz_type cnt=0; cnt
cout<
首先调用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
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;
}
在同一个键上调用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
//loop through the number of entries there are for this author
while(pos.first!=pos.second){
cout<
++pos.first;
}
pair对象的first成员存储lower_bound函数返回的迭代器,而second成员则记录upper_bound函数返回的迭代器。