4

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
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • 2
    Probable dup: http://stackoverflow.com/questions/11554932/how-can-i-get-all-the-unique-keys-in-a-multimap – Shafik Yaghmour Mar 07 '13 at 19:51
  • 1
    Do you need just one (basically randomly chosen) pair for every key, or actually the first (by what metric)? – Grizzly Mar 07 '13 at 19:51
  • @Grizzly: well, what is easier, I don't really need the value on the spot. I could later fetch the value that I want. – rsk82 Mar 07 '13 at 19:54
  • @Shafik that doesn't look like a duplicate to me. This question wants to locate the "first" (whatever that means) *value* for each unique key, and the one you've linked to wants to identify the unique keys themselves (without caring about the values, or which one is "first"). – JBentley Mar 07 '13 at 19:55
  • @rsk82 So you actually just need all the unique keys? – Drew Dormann Mar 07 '13 at 19:57
  • 2
    @DrewDormann: actually yes, from what it works (since I din't know that asking this question) I can get whatever value I want, first, last middle. – rsk82 Mar 07 '13 at 19:59

2 Answers2

8

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;
}
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90
1

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

John Bandela
  • 2,416
  • 12
  • 19