Search code examples
c++multimap

Add values to a std::multimap


I'm trying to print out the five most used values. But when I changed my map to a multimap I broke the code where I add values to the map. How can I add values to a multimap? Can it be done in a similar way as I add values to a map?

// Create a map for keeping track of how many occurences of the different colors
    multimap<string, int> hexmap;

    // Add the hex values to the map
        for(int i = 0; i < imagesize; i ++)
        {
            hexmap[colors[i]]++;
        }

        typedef std::multimap<int, string> Mymap;
        Mymap dst;

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


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

Solution

  • "I'm trying to print out the five most used values."

    In this case, you don't have to use hexmap as std::multimap just std::map will do the job

    However std::multimap for dst should be required