Reputation: 29377
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
Upvotes: 5
Views: 3181
Reputation: 2436
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
Upvotes: 1
Reputation: 13099
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;
}
Upvotes: 9