0

I am using a std::multimap to map from a key to a set of matching values. I have a situation where I want to be able to list/iterate over the unique keys in the map.

How do I get an iterator of the unique keys in a C++ multimap?

Another option is using a map<K, set<V>>, but that requires more manual management.

oconnor0
  • 3,154
  • 6
  • 34
  • 52
  • Do you just want to iterate, or do you want a full-blown iterator that can be passed to template functions and has proper `iterator_traits` and all? – aschepler Aug 16 '13 at 22:08
  • @aschepler, I'm not sure. I want to be able to process & count all values for a single key. I also want to be able to iterate over them. – oconnor0 Aug 16 '13 at 22:15
  • Are you saying something like: `for all keys k: iterate over all key-value pairs corresponding to k`? Or do you just want to iterate over the unique keys? – Michael Oliver Aug 16 '13 at 22:22
  • I believe that `for all keys k: iterate over all key-value pairs corresponding to k` captures what I want to do. If possible, I'd also want to be able to simply get a count of `all key-value pairs corresponding to `k. – oconnor0 Aug 16 '13 at 22:47

1 Answers1

2

If you expect the number of duplicate keys to be small, just keep incrementing the iterator until the key value changes. If you expect the number of duplicate keys to be large, just use upper_bound to get an iterator to the element with the next key value.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278