Question

I have a STL::multimap and I search it with equal_range to return an upper and lower bound. 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;
}
Was it helpful?

Solution

Use std::distance algorithm to find the distance between the iterators. Like:

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

OTHER TIPS

If you just want to count the number of elements with a given key, use count:

int ct = mm.count(5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top