How to determine if an element exists in std :: map?

My use case:

map<string, Car> cars; bool exists(const string& name) { // somehow I should find whether my MAP has a car // with the name provided return false; } 

Could you suggest the best and most elegant way to do this in C ++? Thank.

+43
c ++
May 6 '10 at 14:38
source share
9 answers

Of course use an iterator

 map<string,Car>::const_iterator it = cars.find(name); return it!=cars.end(); 
+42
May 6 '10 at 2:39 pm
source share
 return cars.find(name) != cars.end(); 
+68
May 6 '10 at 2:39 pm
source share

You can also use

 bool exists(const string& name) { return cars.count(name) != 0; } 
+21
May 6 '10 at
source share

Besides the answers to the iterator value from find () and comparison with .end (), there is another way: map :: count.

You can call map :: count (key) with a specific key; it will return the number of records for this key. For cards with unique keys, the result will be 0 or 1. Since the multimap exists with the same interface, it is better to compare it with! = 0 for existence to be safe.

for your example, this

 return (cars.count(name)>0); 

The advantages that I see are: 1. shorter code, 2. benefit from any optimizations that the library can apply internally using its presentation data.

+14
May 2, '13 at 17:56
source share

What about:

 template <typename KeyType, typename Collection> bool exists_in(Collection const& haystack, KeyType const& needle) { return std::find(haystack.begin(), haystack.end(), needle) != haystack.end(); } template <typename K, typename V> bool exists_in(std::map<K,V> const& haystack, K const& needle) { return haystack.find(needle) != haystack.end(); } 

This makes exists_in work with any standard container via std::find and use the special version for std::map , as it offers a more efficient search alternative. You can add additional specializations as needed (for example, for std::set and others).

+7
May 6, '10 at 15:03
source share
 bool exists(const string& name) { return cars.find(name) != cars.end(); } 
+5
May 6 '10 at 2:39 a.m.
source share

std::map::find(const key_type& x );

Returns map::end if the item does not exist.

+2
May 6 '10 at 2:40 pm
source share
 bool exists(const std::map<std::string, Car>& cars, const std::string& name) { return cars.end() != cars.find(name); } 
+1
May 6 '10 at 2:40 a.m.
source share
 #define itertype(v) typeof((v).begin()) itertype(cars) it = cars.find(name); return it != cars.end(); 
0
Jun 04 '17 at 17:55
source share



All Articles