C++ set count()

30 Aug 2024 | 3 分钟阅读

C++ set count() 函数用于返回容器中找到的元素数量。由于 set 容器不包含任何重复元素,此函数实际上在元素值 val 存在于 set 容器中时返回 1,否则返回 0。

语法

参数

val:要在 set 容器中搜索的值。

返回值

如果元素值 val 存在于 set 容器中,则返回 1,否则返回 0。

复杂度

大小的对数。

迭代器有效性

无变化。

数据竞争

容器被访问。

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

异常安全

如果抛出异常,容器中没有变化。

示例 1

我们来看一个搜索给定键值元素的简单示例

输出

The key 30 is present
The key 100 is not present

在上面的示例中,count() 函数检查给定值。如果元素存在于 set 容器中,它将显示元素存在的消息,否则显示不存在。

示例 2

我们来看一个搜索 set 元素的简单示例

输出

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

在上面的示例中,count() 函数用于在 set 中搜索 'a' 到 'h' 的元素。

示例 3

我们来看一个搜索 set 中键的简单示例

输出

'a' is present in the set 
'z' is not present in the set

在上面的示例中,键 'a' 存在于 set m 中,因此它将是 'a' 的值,而键 'z' 不存在于 set 中,因此 'z' 没有值。

示例 4

让我们看一个简单的例子

输出

The number of elements in s1 with a sort key of 1 is: 1.
The number of elements in s1 with a sort key of 2 is: 0.