public member function
<set>
std::set::count
size_type count (const value_type& val) const;
Count elements with a specific value
Searches the container for elements equivalent to val and returns the number of matches.
Because all elements in a set container are unique, the function can only return 1 (if the element is found) or zero (otherwise).
Two elements of a set are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
Parameters
- val
- Value to search for.
Member type value_type is the type of the elements in the container, defined in set as an alias of its first template parameter (T).
Return value
1 if the container contains an element equivalent to val, or zero otherwise.
Member type size_type is an unsigned integral type.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// set::count
#include <iostream>
#include <set>
int main ()
{
std::set<int> myset;
// set some initial values:
for (int i=1; i<5; ++i) myset.insert(i*3); // set: 3 6 9 12
for (int i=0; i<10; ++i)
{
std::cout << i;
if (myset.count(i)!=0)
std::cout << " is an element of myset.\n";
else
std::cout << " is not an element of myset.\n";
}
return 0;
}
| |
Output:
0 is not an element of myset.
1 is not an element of myset.
2 is not an element of myset.
3 is an element of myset.
4 is not an element of myset.
5 is not an element of myset.
6 is an element of myset.
7 is not an element of myset.
8 is not an element of myset.
9 is an element of myset.
|
Complexity
Logarithmic in size.
Iterator validity
No changes.
Data races
The container is accessed.
Concurrently accessing the elements of a set is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
See also
- set::find
- Get iterator to element (public member function
)
- set::size
- Return container size (public member function
)
- set::equal_range
- Get range of equal elements (public member function
)