vendredi 19 août 2016

Returning zero when the key is not exist in unordered_map

I have the following container:

std::unordered_map<uint8_t,int> um;

um is assumed to have keys between 0 and 255 but not all of them. So, in certain point of time I want to ask it to give me the value of the key 13 for example. If it was there, I want its value (which is guaranteed to be not 0). If not, I want it to return 0.

What is the best way (performance point of view) to implement this?

What I tried till now: use find and return 0 if it was not found or the value if it was found.

P.S. Changing to std::vector<int> that contains 256 items is not an option. I can not afford the space to storing 256 values always.


EDIT:

My problem is histogram computing problem keys (colors 0-255) values(frequent, int is enough). I will not be satisfied if I just know that some key is exist or not. I also need the value (the frequent).

Additional information:

  • I will never erase any item.
  • I will add items sometimes (at most 256 items) and usually less than 10.
  • I will query on key so so many times.
  • Usually querying and inserting come with no specific order.

Aucun commentaire:

Enregistrer un commentaire