Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether an element exists in std::map?

Tags:

c++

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.

like image 996
yegor256 Avatar asked May 06 '10 14:05

yegor256


People also ask

How do you check if an element is already present in a map?

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.

What does C++ map return if key not found?

If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().

How do you find the value of an element on a map?

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.

Is key in map C++?

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.


1 Answers

return cars.find(name) != cars.end(); 
like image 83
kennytm Avatar answered Oct 09 '22 01:10

kennytm