Travis
Travis

Reputation: 2008

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. 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;
}

Upvotes: 9

Views: 10092

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

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

int ct = mm.count(5);

Upvotes: 2

Naveen
Naveen

Reputation: 73443

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

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

Upvotes: 26

Related Questions