5

I have such a map:

std::map<time_t, int>

There is one value (int) per day (time_t). Some days may have the same value and therefore may not be unique. I need to perform a calculation for each unique int value from this map.

What is the quickest (least CPU usage) way to retrieve them?

d-_-b
  • 6,555
  • 5
  • 40
  • 58
  • Are you allowed to change `std::map` to a different data structure? – Luchian Grigore Feb 21 '12 at 08:38
  • @LuchianGrigore, Sure why not. As long as I don't lose any data. – d-_-b Feb 21 '12 at 08:43
  • 1
    The answer to "quickest" will be different depending (among other things) how many times you need to get the unique ints, per modification of the main `map`. If that number is large, then you should maintain a collection for the values (either a separate `multiset`, a separate `map` to keep a count, or using Boost.MultiIndex, and in each case the set/map could be ordered or unordered). If the number is sufficiently small, then it would be faster to avoid the overhead on every map modification, and just copy the values into a new set or unordered_set each time you need them. – Steve Jessop Feb 21 '12 at 09:15
  • @SteveJessop, Thanks for the tips on performance. The number of pairs is relatively small < 1000. So I think I'll with stuffing them into a set. – d-_-b Feb 21 '12 at 09:17

1 Answers1

3

Do you have memory constraints? If not, I would keep an std::set (or whichever hash_set is available in your environment) listing the unique integers.

If you absolutely cannot allocate more memory, maybe you should consider using a different data structure in the first place.

Guy Adini
  • 5,188
  • 5
  • 32
  • 34
  • Let's say memory is not an issue. How would I keep track of the days? – d-_-b Feb 21 '12 at 09:09
  • Keep your original data structure, and an additional one. There are two options for the 2nd data structure: (a) keep an std::set which simply lists which values of unique integers (if that's all you need). (b) keep an std::map, listing all of the days that a given value appeared in. – Guy Adini Feb 21 '12 at 09:13
  • And whenever you insert into the original map, also insert into the supporting data structure. – Guy Adini Feb 21 '12 at 09:14
  • If you keep a `set` of values, then what do you do to it when you remove an element from the original `map`? – Steve Jessop Feb 21 '12 at 09:18
  • 1
    If that ever happens, you must stick with option 2 (keep a "bidirectional map" - so you have a list/set of days mapped for each value, and remove from that, removing the value entirely if all of the days it appeared on are removed). – Guy Adini Feb 21 '12 at 09:28
  • Instead of a bidirectional map, the reverse structure could just map from value to a count of how many times it appears in the forward map. When the count reduces to zero, then the value can be removed. – Toby Speight Jun 07 '19 at 11:03