0

Sometimes I want check if a std::unordered_map container contains an element, that's all I want to know, I don't want an iterator, I don't want to check the iterator against end(). Say for std::unordered_map<int, int>:

if (mymap.contains(5)) // Do something;

Instead of:

auto it = mymap.find(5);
if (it != mymap.end()) Do something;

What's the best way to have this?

Zebrafish
  • 9,170
  • 2
  • 28
  • 78
  • Use [C++ 20](https://en.cppreference.com/w/cpp/container/map/contains)? – PaulMcKenzie Oct 02 '20 at 07:05
  • But why? In the case you check, find the need of further processing, you have AGAIN to get the iterators. Operate via `contains` or `count` comes with a cost! – Klaus Oct 02 '20 at 08:03

3 Answers3

3

The C++ designers have finally caught on to the fact that this is such a common operation, and have kindly added std::unordered_map::contains to the language in C++20.

If you can't use C++20 yet, you can always write your own implementation as a free function:

template<typename M, typename T>
bool contains(M const &map, T const &element) {
  return map.find(element) != map.end();
}
Thomas
  • 150,847
  • 41
  • 308
  • 421
1

std::unordered_map supports contains since C++20.

bool contains( const Key& key ) const;
template< class K > bool contains( const K& x ) const;

Before C++20 you can use count, e.g.

if (mymap.count(5) == 1) // Do something;
songyuanyao
  • 147,421
  • 15
  • 261
  • 354
0

Before C++20 you can use std::unordered_map::count:

if (mymap.count(5)) // Do something;

Some like to be explicit and write

if (mymap.count(5) == 1) 

though thats a matter of style and it appears that you want to avoid an explicit comparison.

Note that a map either contains the key or not, so despite its name count does not really "count". The result is either 0 or 1.

Since C++20 there is std::unodered_map::contains that returns a bool.

463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126
  • Are there any disadvantages to just creating your own class, inheriting from std::unordered map and adding extra functions? – Zebrafish Oct 02 '20 at 10:58
  • @Zebrafish publicly inheriting from std containers isnt a good idea, their destructor isnt virtual. If you inherit privately, you would need to forward the complete interface. In general free functions are prefered over member function when possible (have to look for a reference...) – 463035818_is_not_a_number Oct 02 '20 at 11:03
  • @Zebrafish https://stackoverflow.com/questions/21028773/free-function-versus-member-function I would rather go for a `bool contains( std::unodered_map, KeyType)` as suggested in the other answer – 463035818_is_not_a_number Oct 02 '20 at 11:04