cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Containers : set : count
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
set
comparison operators
set::set
set::~set
member functions:
· set::begin
· set::clear
· set::count
· set::empty
· set::end
· set::equal_range
· set::erase
· set::find
· set::get_allocator
· set::insert
· set::key_comp
· set::lower_bound
· set::max_size
· set::operator=
· set::rbegin
· set::rend
· set::size
· set::swap
· set::upper_bound
· set::value_comp

-

set::count public member function
size_type count ( cont key_type& x ) const;

Count elements with a specific key

Searches the container for an element with a key of x and returns the number of times the element appears in the container. Because set containers do not allow for duplicate keys, this means that the function actually returns 1 if the element is found, and zero otherwise.

Parameters

x
Value to be searched for.
key_type is a member type defined in set containers as an alias of Key, which is the first template parameter and the type of the elements stored in the container.

Return value

1 if an element with a key equivalent to x is found, or zero otherwise.

Member type size_type is an unsigned integral type.

Example

// set::count
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  set<int> myset;
  int i;

  // set some initial values:
  for (i=1; i<5; i++) myset.insert(i*3);    // set: 3 6 9 12

  for (i=0;i<10; i++)
  {
    cout << i;
    if (myset.count(i)>0)
      cout << " is an element of myset.\n";
    else 
      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.

See also

set::find Get iterator to element (public member function)
set::size Return container size (public member function)
set::lower_bound Return iterator to lower bound (public member function)
set::upper_bound Return iterator to upper bound (public member function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us