So I'm trying to iterate through the map from greatest to least and it has to print the top 10. I have to use map.h because its required so I can't use the normal map, I also cant use a vector. How would I just get the top 10 from the map from descending order?
Here is the link to the Stanford Map Library
#include <iostream>
#include "map.h"
using namespace std;
Map <string, int> wordFreq;
int counter = 0;
int max = 0;
for(string s : wordFreq)
{
if(wordFreq[s] > max)
{
counter ;
max = wordFreq[s];
cout << s << " : " << max << endl;
}
if(counter == 10)
{
exit(0);
}
}
I've been at this for a couple of hours so I think my logic is just bad.
CodePudding user response:
If you only need top 10
value, you should use a minHeap with a size of 10 as you don't need to sort all the elements in the map.
Then sort the elements in minHeap before return if you need(maybe unsorted top10 values are excepted).
CodePudding user response:
This class has no way to iterate it other than a "visit all" function. So there's not going to be any good way to do it.
A simple hack is as follows:
- Flip the sign of every
int
you use as a key before storing it in the map. - This will cause the map to visit its elements in reverse order.
- Call
mapAll
with a visitor function that only prints the first ten times it's called. Don't forget to flip the sign of each key before printing it.
A less hacky way is to create reversedInt
class that acts like an int
but compares in reverse. That will avoid the need to flip signs and still let the map traverse in reverse.
It seems the provided Map
class can accept a comparator in its constructor. So this might be the intended way to do this, I guess.
But the provided Map
class is really just not suitable for this use.