Chinaunix首页 | 论坛 | 博客
  • 博客访问: 801744
  • 博文数量: 330
  • 博客积分: 9641
  • 博客等级: 中将
  • 技术积分: 3181
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
文章分类

全部博文(330)

文章存档

2012年(17)

2011年(135)

2010年(85)

2009年(57)

2008年(36)

我的朋友

分类: C/C++

2010-12-29 13:41:27

声明

multimap 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::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::size_type sz_type;

sz_type entries=author.count(search_item);

//get iterator to the first entry for this author

multimap::iterator iter=author.find(search_item);

//loop through the number of entries there are for this author

for(sz_type cnt=0; cnt

  cout<second<//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::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<second<//print each title

++beg;

}

在同一个键上调用lower_boundupper_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 pos=authors.equal_range(search_item);

//loop through the number of entries there are for this author

while(pos.first!=pos.second){

   cout<second<;//print each titile

   ++pos.first;

}

pair对象的first成员存储lower_bound函数返回的迭代器,而second成员则记录upper_bound函数返回的迭代器。

阅读(714) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~