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的元素是安全的。

異常安全

強保證:如果丟擲異常,容器沒有發生變化。

另見