cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Containers : map : 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
map
comparison operators
map::map
map::~map
member functions:
· map::begin
· map::clear
· map::count
· map::empty
· map::end
· map::equal_range
· map::erase
· map::find
· map::get_allocator
· map::insert
· map::key_comp
· map::lower_bound
· map::max_size
· map::operator=
· map::operator[]
· map::rbegin
· map::rend
· map::size
· map::swap
· map::upper_bound
· map::value_comp

-

map::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 elements having that key. Because map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key is found, and zero otherwise.

Parameters

x
Key value to be searched for.
key_type is a member type defined in map containers as an alias of Key, which is the first template parameter and the type of the keys for 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

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

int main ()
{
  map<char,int> mymap;
  char c;

  mymap ['a']=101;
  mymap ['c']=202;
  mymap ['f']=303;

  for (c='a'; c<'h'; c++)
  {
    cout << c;
    if (mymap.count(c)>0)
      cout << " is an element of mymap.\n";
    else 
      cout << " is not an element of mymap.\n";
  }

  return 0;
}

Output:

a is an element of mymap.
b is not an element of mymap.
c is an element of mymap.
d is not an element of mymap.
e is not an element of mymap.
f is an element of mymap.
g is not an element of mymap.

Complexity

Logarithmic in size.

See also

map::find Get iterator to element (public member function)
map::size Return container size (public member function)
map::equal_range Get range of equal elements (public member function)

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