每天一点C++——获取multimap某个key的所有value

multimap中可以保存多个key值,介绍一下获取某一key值所有value的方法。这些方法对于multiset也是可以使用的。

  1. 使用equal_range
  2. 使用count统计出数量
  3. 使用lower_bound upper_bound获取起止迭代器,和1类似

代码:

#include <iostream>
#include <map>

using namespace std;

typedef multimap<string, string>::iterator It;
int main() {
    multimap<string, string> names;

    names.insert(pair<string, string>("zhang", "san"));
    names.insert(pair<string, string>("li", "si"));
    names.insert(pair<string, string>("wang", "wu"));
    names.insert(pair<string, string>("zhao", "liu"));
    names.insert(pair<string, string>("zhang", "qi"));
    names.insert(pair<string, string>("zhang", "ba"));

    //use equal_range
    pair<It, It> ret;

    ret = names.equal_range("zhang");
    for(It it = ret.first; it != ret.second; ++it) {
        cout << " " << it->second;
    }
    cout << "\n";

    //use count
    It it = names.find("zhang");
    for (int i = 0, len = names.count("zhang"); i < len; ++i, ++it) {
        cout << " " << it->second;
    }
    cout << "\n";

    //use upper_bound  lower_bound
    It start, end;
    start = names.lower_bound("zhang");
    end = names.upper_bound("zhang");

    for (It it = start; it != end; ++it) {
        cout << " " << it->second;
    }
    cout << "\n";
    return 0;
}
  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值