Search code examples
c++multimap

How to find the total number of values for a particular Key in Multimap C++


I have created a multimap with key as the Mod value and VALUE as the number being modded. Just like a hash table.

vector<int> A{1,2,3,4,5,6,7,8,9};
int n=A.size();
multimap<int,int> mymap;

int sqvalue=sqrt(n);

for(int i=0;i<n;i++)
{
   int temp=A[i]%sqvalue;
   mymap.insert(pair<int,int>(temp,A[i]));
}

Q1. How to obtain the total number of VALUES for all the KEYS ? e.g How many numbers exist in Key no.2.? Q2. How to print all the values wrt to its Keys ?

Thanks.


Solution

  • You can use equal_range, which returns a range containg all the values with given key.

    auto rng = myMap.equal_range(key);
    // e.g. sum of the valuse
    auto sum = std::accumulate(rng.first, rng.second, 0);
    // Or print
    for(auto it = rng.first; it != rng.second; ++it)
          std::cout<<elm->second;