C++ unordered_set count() Function
Example
Check if "BMW" and "Tesla" exist in an unordered set:
unordered_set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars.count("BMW") << "\n";
cout << cars.count("Tesla");
Definition and Usage
The count() function returns the number of elements with the given value.
An unordered set cannot have two equal elements, so the result is always 1 (the value exists) or 0 (the value does not exist). This makes count() an easy way to check if a value exists.
The count function is defined in the <unordered_set> header file.
Tip: Use find() if you also want an iterator to the element.
Syntax
unordered_set.count(type value)
type is the type of the elements in the unordered set, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to search for. |
Technical Details
| Returns: | The number of elements with the given value: 1 or 0. |
|---|
Related Pages
Read more about unordered sets in our Unordered Set Tutorial.