"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
Вопрос
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;
Решение 2
"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
Другие советы
You add elements to a std::multimap<K, V>
using insert()
or emplace()
, e.g.:
std::multimap<std::string, int> map;
map.insert(std::make_pair("hello" , 1));
map.insert({ "world", 0 });
map.emplace("hello", 0);
You'd locate objects in the std::multimap<K, V>
using it's find()
member, e.g.:
std::multimap<std::string, int>::iterator it = map.find("hello");