public member function
<map>
size_type count (const key_type& k) const;
Count elements with a specific key
Searches the container for elements with a key equivalent to k and returns the number of matches.
Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
Parameters
- k
- Key to search for.
Member type key_type is the type of the element keys in the container, defined in map as an alias of its first template parameter (Key).
Return value
The number of elements in the container contains that have a key equivalent to k.
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 23 24 25 26
|
// multimap::count
#include <iostream>
#include <map>
int main ()
{
std::multimap<char,int> mymm;
mymm.insert(std::make_pair('x',50));
mymm.insert(std::make_pair('y',100));
mymm.insert(std::make_pair('y',150));
mymm.insert(std::make_pair('y',200));
mymm.insert(std::make_pair('z',250));
mymm.insert(std::make_pair('z',300));
for (char c='x'; c<='z'; c++)
{
std::cout << "There are " << mymm.count(c) << " elements with key " << c << ":";
std::multimap<char,int>::iterator it;
for (it=mymm.equal_range(c).first; it!=mymm.equal_range(c).second; ++it)
std::cout << ' ' << (*it).second;
std::cout << '\n';
}
return 0;
}
| |
Output:
There are 1 elements with key x: 50
There are 3 elements with key y: 100 150 200
There are 2 elements with key z: 250 300
|
Complexity
Logarithmic in size, plus linear in the number of matches.
Iterator validity
No changes.
Data races
The container is accessed.
No mapped values are accessed: concurrently accessing or modifying elements is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.