您的位置:首页 > 其它

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

2015-09-29 03:09 176 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: