Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop multimap only to get first key-value pairs for every key?

For example if I have such mmap:

alice -> 30
bob -> 23
josh -> 20
josh -> 30
andy -> 40
andy -> 40

to get only this pairs:

alice -> 30
bob -> 23
josh -> 20
andy -> 40
like image 565
rsk82 Avatar asked Jan 14 '23 00:01

rsk82


2 Answers

This oughta do it as clean, and effective, as possible:

for(auto it = m.begin(); it != m.end(); it = m.upper_bound(it->first)) {
  std::cout << it->first << ":" << it->second << std::endl;
}
like image 159
Viktor Sehr Avatar answered Jan 25 '23 16:01

Viktor Sehr


Here is a short answer, but not the most efficient

multimap<string, int> mm;
// Add stuff to multimap

// Map with only the first items from multimap
map<string,int> m;

for(auto iter = mm.rbegin(); iter != mm.rend(); ++iter){
   m[iter->first] = iter->second;
}

This works because we start from the end. Thus any duplicate keys in multimap will overwrite the previous key in map. Since we start from the end, we should have the first key

like image 31
John Bandela Avatar answered Jan 25 '23 15:01

John Bandela