简体   繁体   中英

Top 5 values from std::map

I have a function already that takes out the key value with the most mapped value.

// Function for finding the occurances of colors or in this case hex values
void findOccurrances(double * mostNumTimes, map<string, int>  &hexmap, string * colorlist)
{
    map<string,int>::iterator it = hexmap.begin();

    for( ;it != hexmap.end(); it ++)
    {   
        if(*mostNumTimes <= it->second)
        {
                *mostNumTimes = it->second;
                *colorlist = it->first;
        }
    }
}

Is there an easy way to expand it to show the top five results? I know you can copy it to a vector and what not but I'm wanting an easier way of doing it.

Copying into a vector isn't that difficult:

typedef std::pair<string, int> Pair;
std::vector<Pair> contents(hexmap.begin(), hexmap.end());

Done.

But to find the top 5, believe it or not <algorithm> has a function template that does exactly what you want. In C++11, which usefully has lambdas:

std::vector<Pair> results(5);
std::partial_sort_copy(
    hexmap.begin(), hexmap.end(), 
    results.begin(), results.end(), 
    [](const Pair &lhs, const Pair &rhs) { return lhs.second > rhs.second; }
);

results now contains the top 5 entries in descending order.

I'd interchange the key and value and create new map

std::map<int,std::string> dst;

std::transform(hexmap.begin(), hexmap.end(), 
               std::inserter(dst, dst.begin()), 
               [](const std::pair<std::string,int> &p ) 
               { 
                 return std::pair<int,std::string>(p.second, p.first); 
               }
               );

And now print top five values of dst in usual way,

typedef std::map<int, std::string> Mymap;
Mymap::iterator st = dst.begin(), it;
size_t count = 5;
for(it = st; ( it != dst.end() ) &&  ( --count ); ++it)
  std::cout << it->second << it->first <<std::endl ;

Edit :

Use a std::multimap if there are same int (value) for more than one std::string (key) in your hexmap

I have a little bit confused about the arguments. why you write the function in this way, And I try for this.

string colorlist;
double max_val = 0;

for (int i = 0; i < 5; ++i)
{
    findOccurrances(&max_val, hexmap, &colorlist);

    cout << colorlist << " " << max_val << endl; // to do something

    mapStudent.erase(colorlist);
}

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