Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 290
Travis Avatar asked Nov 09 '09 06:11

Travis


People also ask

How do you access the elements of a multimap?

multimap::find( ) an inbuilt function in C++ STL, which is defined in <map> header file. find() searches elements in the container which are associated with key K. This function returns an iterator pointing to the single element in a container. It returns an iterator if the element found in the container.

How do I get the size of a multimap in C++?

multimap::size() function is an inbuilt function in C++ STL, which is defined in <map> header file. size() is used to check the size of the multimap container. This function gives size or we can say gives us the number of elements in the multimap container associated.

What is the use of multimap?

Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always.

What is a multimap C++?

The C++ Standard Library multimap class is used for the storage and retrieval of data from a collection in which each element is a pair that has both a data value and a sort key. The value of the key doesn't need to be unique and is used to order the data automatically.


2 Answers

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

int ct1 = std::distance(ret.first, ret.second);
like image 50
Naveen Avatar answered Sep 19 '22 14:09

Naveen


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

int ct = mm.count(5);
like image 35
Mike Seymour Avatar answered Sep 21 '22 14:09

Mike Seymour