C++ set count() Function
Example
Check if "BMW" and "Tesla" exist in a set:
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.
A 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 <set> header file.
Tip: Use find() if you also want an iterator to the element.
Syntax
set.count(type value)
type is the type of the elements in the set, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to look for. |
Technical Details
| Returns: | The number of elements with the given value: 1 or 0. |
|---|
Related Pages
Read more about sets in our Sets Tutorial.