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 please suggest the best and the most elegant way to do it in C++? Thanks.
You can call map::count(key) with a specific key; it will return how many entries exist for the given key. For maps with unique keys, the result will be either 0 or 1. Since multimap exists as well with the same interface, better compare with != 0 for existence to be on the safe side.
If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().
Search by value in a Map in C++ Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”. Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.
Use the std::map::contains Function to Check if Key Exists in a C++ Map. contains is another built-in function that can be used to find if the key exists in a map . This function returns a boolean value if the element with the given key exists in the object.
return cars.find(name) != cars.end();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With