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

Travis picture Travis · Nov 9, 2009 · Viewed 7.9k times · Source

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

Answer

Naveen picture Naveen · Nov 9, 2009

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

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