multiMap遍历方法

来源:互联网 发布:软件项目经理面试 编辑:程序博客网 时间:2024/06/06 01:51

multimap是map升级版,仍然是key-value,但这个key允许重复




代码来源:http://www.cnblogs.com/dongsheng/archive/2013/09/10/3311594.html

/*    multimap中的三种遍历方法    multimap中如果没有查找到相应元素,则返回的迭代器是依据该元素的排列顺序该键应该插入的位置    如果找不到,则方法一和方法二返回的两个迭代器应该相等*/#include <iostream>#include <map>#include <string>#include <utility>using namespace std;int main(){    multimap<string, string> mulMap;    mulMap.insert(make_pair("鲁迅", "朝花夕拾"));    mulMap.insert(make_pair("鲁迅", "阿Q正传"));    mulMap.insert(make_pair("鲁迅", "野草"));    mulMap.insert(make_pair("罗贯中", "三国演义"));    mulMap.insert(make_pair("罗贯中", "隋唐志传"));    mulMap.insert(make_pair("琼瑶", "还珠格格"));    mulMap.insert(make_pair("琼瑶", "情深深雨蒙蒙"));    typedef multimap<string, string>::iterator multiMapItor;    //方法一:推荐        string author("鲁迅");    cout << author << "的书籍有:" << endl;    pair<multiMapItor, multiMapItor> pos = mulMap.equal_range(author);    while(pos.first != pos.second)    {        cout << pos.first->second << endl;        ++pos.first;    }    cout << endl;    //方法二:    author.assign("罗贯中");    cout << author << "的书籍有:" << endl;    multiMapItor beg = mulMap.lower_bound(author);    multiMapItor end = mulMap.upper_bound(author);    while(beg != end)    {        cout << beg->second << endl;        ++beg;    }    cout << endl;    //方法三:不推荐    author.assign("琼瑶");    cout << author << "的书籍有:" << endl;    typedef multimap<string, string>::size_type sz_type;    sz_type entries = mulMap.count(author);    multiMapItor itor = mulMap.find(author);    for(sz_type cnt = 0; cnt != entries; ++cnt)        cout << (itor++)->second << endl;    system("pause");    return 0;}


原创粉丝点击