Chinaunix首页 | 论坛 | 博客
  • 博客访问: 250165
  • 博文数量: 78
  • 博客积分: 1465
  • 博客等级: 上尉
  • 技术积分: 972
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-28 13:46
文章分类

全部博文(78)

文章存档

2012年(1)

2011年(9)

2010年(68)

我的朋友

分类: C/C++

2010-01-11 00:32:19


 假定有作者和书名的映射,我们可能希望找到并输出某个作者写的所有书的书名。映射存放在multimap里面。(multiset可依次类推)
方法一:

    multimap<string,string> authors;
    string search_item("Alain de Botton");
//假定作者是Alain de Botton
    typedef multimap<string,string>::size_type sz_type;
    sz_type entries = authors.count(search_item)
//计算一共有多少个关联键search_item的元素
    multimap<string,string>::iterator iter = authors.find(search_item);
//返回第一个关联键search_item的元素的迭代器
    for ( sz_type cnt=0; cnt !=entries ; ++cnt, ++iter )
    {
        cout<< iter->second<<endl;
    }


方法二:
    首先熟悉以下三个函数:
    m.lower_bound(k);   返回一个迭代器,指向键不少于k的第一个元素
    m.upper_bound(k);   返回一个迭代器,指向键大于k的第一个元素
    m.equal_bound(k);   返回一个迭代器的pair对象,它的first成员等价于m.lower_bound(k),second成员等价于m.upper_bound(k)。
    于是方法一的代码可以写成如下两种方式

    typedef multimap<string,string>::iterator authors_it;
    authors_it beg = authors.lower_bound(search_item),
               end = authors.upper_bound(search_item);
    while beg != end )
    {
        cout << beg->second <<endl;
        ++beg; 
    }


    和

    typedef multimap<string,string>::iterator authors_it;
    pair<authors_it,authors_it> pos = authors.equal_range(search_item);
    while(pos.first != pos.second)
    {
        cout<<pos.first->second<<endl;
        ++pos.first; 
    }

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