C++ multiset count()

30 Aug 2024 | 3 分钟阅读

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

语法

参数

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

返回值

如果在 multiset 容器中存在值为 val 的元素,则返回 1,否则返回 0。

复杂度

大小的对数。

迭代器有效性

无变化。

数据竞争

容器被访问。

同时访问容器中的元素是安全的。

异常安全

如果抛出异常,multiset 中不会发生任何更改。

示例 1

让我们看一个简单的例子来搜索具有给定键值的元素

输出

The key 30 is present
The key 100 is not present

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

示例 2

让我们看一个简单的例子来搜索 multiset 的元素

输出

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

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

示例 3

让我们看一个简单的例子来搜索 multiset 中的键

输出

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

在上面的例子中,键 'a' 存在于 multiset m 中,因此它将是 'a' 的值,而键 'z' 不存在于 multiset 中,因此没有 '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.
下一个主题C++ multiset