multimap容器查找元素的三种方法总结

来源:互联网 发布:xp系统网络ip地址设置 编辑:程序博客网 时间:2024/05/29 14:41

1、使用find和count操作。代码分析:
string search_item(“Alain de Botton”);
typedef multimap<string,string> :: size_type sz_type;
sz_type entries=author.count(search_item);
multimap<string,string> :: iterator iter=author.find(search_item);
for(sz_type cnt=0;cnt!=entries;++cnt,++iter){
cout<< iter->second << endl;
上面这段代码就是能够将键为”Alain de Botton”的所有元素给找出来了。自然前提条件有:(1)在multimap中同一个键所关联的元素是相邻存放的;(2)author.find(search_item)这段代码表达的意思是指向的是拥有这个键的第一个实例的迭代器。

2、与众不同的面向迭代器的查找方案。代码讲解:
typedef multimap<string,string> :: iterator anthors_it;
authors_it beg=authors.lower_bound(search_item),
end=authors.upper_bound(search_item);
while(beg!=end){
cout<< beg->second<< endl;
++beg;}
上面这段代码比较简单起到了和第一种方法一样的效果。这种查找方式利用到了两个函数:(1)lower_bound(k);//返回一个迭代器,指向键不小于k的第一个元素;
(2)upper_bound(k);//返回一个迭代器,指向大于k的第一个元素;
上面beg指向该键中第一个与之匹配的元素,而end指向拥有键的最后一个元素的下一个位置。这两个操作不会说明键是否存在,其关键之处在于返回值给出了迭代器范围。

3、equal_range函数。代码讲解:
pair<authors_it,authors_it> pos=authors.equal_range(search_item);
while(pos.first!=pos.second){
cout<< pos.first->second<< endl;
++pos.first;}
上面这段代码也是起到了前两个代码同样的效果,主要是用到了equal_range函数:equal_range(k) //返回一个迭代器的pair对象,它的first成员等价于lower_bound(k),而second成员则等价于upper_bound(k).

注意:item->mem //对item进行解引用,获取指定元素中名为mem的成员,等效于(*item).mem

1 0
原创粉丝点击