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

I have an STL :: multimap and I am looking for it with equal_range to return the upper and lower bounds. Can I find the number of elements in this range without repeating all of them and counting them one at a time?

#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;
}
+5
source share
2 answers

Use the algorithm std::distanceto find the distance between iterators. How:

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

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

int ct = mm.count(5);
+1
source

All Articles