简体   繁体   English

C ++查找STL :: multimap范围内的元素数

[英]C++ Find the number of elements in a range from an STL::multimap

I have a STL::multimap and I search it with equal_range to return an upper and lower bound. 我有一个STL :: multimap,我用equal_range搜索它以返回一个上限和下限。 Can I find the number of elements in this range without iterating through them all and counting them one by one? 我可以找到这个范围内的元素数量而不是迭代它们并逐个计算它们吗?

#include <iostream>
#include <map>

using namespace std;

int main () {
    multimap<int,int> mm;
    pair<multimap<int, int>::iterator,multimap<int, int>::iterator> ret;
    multimap<int,int>::iterator retit;

    for (int n=0; n<100; n++) {
        mm.insert ( make_pair( rand()%10,rand()%1000) );
    }

    ret = mm.equal_range(5);

    int ct = 0;
    for (retit=ret.first; retit!=ret.second; ++retit) {
        cout << retit->second << endl;
            ct++;
    }
    cout << ct << endl;

    return 0;
}

Use std::distance algorithm to find the distance between the iterators. 使用std::distance算法查找迭代器之间的距离。 Like: 喜欢:

int ct1 = std::distance(ret.first, ret.second);

如果您只想计算给定键的元素数,请使用count

int ct = mm.count(5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM