0

std::unordered_map::find search for the certain key in the unordered_map, and is there a function to search a certain value?

Definitely I can write some simple loop to do it but maybe something already exist for that that?

Bruice
  • 63
  • 6
  • 3
    No because it would be inefficient and the designers of the Standard Library didn't want to encourage inefficient code. – Richard Critten Jul 13 '21 at 22:33
  • 4
    People usually use multi-index containers for this, for example https://www.boost.org/doc/libs/1_76_0/libs/multi_index/doc/index.html – SergeyA Jul 13 '21 at 22:34
  • 1
    If you find yourself doing this reverse look-up frequently you may have to rethink the algorithm or which of the two should really be the key. – user4581301 Jul 13 '21 at 22:40

1 Answers1

2

No, not really. The map entries (key-value pairs) are not arranged according to their values; nor are the values stored separately from the keys etc. Or rather - the standard doesn't guarantee any of that, and all popular implementations don't offer this.

You're just going to have to use a linear search... or a different/additional data structure which supports the kind of searches you need.

Also remember that std::unordered_map is quite slow in practical, non-asymptotic terms, so if performance is a consideration - definitely look for alternatives.

einpoklum
  • 118,144
  • 57
  • 340
  • 684