简体   繁体   中英

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? eg How many numbers exist in Key no.2.? Q2. How to print all the values wrt to its Keys?

Thanks.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM