您的位置:首页 > 编程语言 > C语言/C++

【C++ 学习笔记】:STL-multimap

2011-08-09 15:19 239 查看
multimap提供了可以一种可以有重复键值的STL map类型。其插入方式和map相似,但是由于可以拥有重复键值所以在查找方面有些不同。

查找

1. 直接找到每种键值的所有元素的第一个元素的游标

通过函数:lower_bound( const keytype& x ), upper_bound( const keytype& x ) 可以找到比指定键值x的小的键值的第一个元素和比指定键值x大的键值的第一个元素。返回值为该元素的游标。

细节:当到达键值x已经是最大时,upper_bound返回的是这个multimap的end游标。同理,当键值x已经是最小了,lower_bound返回的是这个multimap的begin游标。

2. 指定某个键值,进行遍历

可以使用上面的lower_bound和upper_bound函数进行游历,也可以使用函数equal_range。其返回的是一个游标对。游标对pair::first是由函数lower_bound得到的x的前一个值,游标对pair::second的值是由函数upper_bound得到的x的后一个值。

样例如下:

multimap<int,int> a;
a.insert(pair<int,int>(1,11));
a.insert(pair<int,int>(1,12));
a.insert(pair<int,int>(1,13));
a.insert(pair<int,int>(2,21));
a.insert(pair<int,int>(2,22));
a.insert(pair<int,int>(3,31));
a.insert(pair<int,int>(3,32));

multimap<int,int>::iterator p_map;
pair<multimap<int,int>::iterator, multimap<int,int>::iterator> ret;

for(p_map = a.begin() ; p_map != a.end();)
{
cout<<p_map->first<<" =>";
ret = a.equal_range(p_map->first);
for(p_map = ret.first; p_map != ret.second; ++p_map)
cout<<""<< (*p_map).second;
cout<<endl;
}


结果:

1 => 11 12 13
2 => 21 22
3 => 31 32
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: