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).

set 的两个元素被认为是等效的,如果容器的 比较对象 返回falsereflexively (i.e., no matter the order in which the elements are passed as arguments).

参数

val
Value to search for.
成员类型value_type是容器中元素的类型,在 set 中定义为其第一个模板参数的别名(T).

返回值

1if the container contains an element equivalent to val, or zero otherwise.

成员类型size_type是一种无符号整型类型。

示例

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;
}

输出
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.


复杂度

size 的对数复杂度。

迭代器有效性

没有变化。

数据竞争

访问容器。
并发访问set的元素是安全的。

异常安全

强保证:如果抛出异常,容器没有发生变化。

另见