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;
}
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.
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.
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.
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.
Use std::distance
algorithm to find the distance between the iterators. Like:
int ct1 = std::distance(ret.first, ret.second);
If you just want to count the number of elements with a given key, use count
:
int ct = mm.count(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With