现在的位置: 首页 > 综合 > 正文

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

2013年10月17日 ⁄ 综合 ⁄ 共 1021字 ⁄ 字号 评论关闭

 

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

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

抱歉!评论已关闭.