📜  C++ STL中的multiset count()函数(1)

📅  最后修改于: 2023-12-03 14:39:52.124000             🧑  作者: Mango

C++ STL中的multiset count()函数

在C++ STL中,multiset是一种可重复集合容器,允许存储重复的元素,且自动按照元素的升序排列。multiset中提供了count()函数,用于统计指定元素在multiset中出现的次数。

count()函数的语法

count()函数的语法如下:

size_t count(const Key& key) const;

其中,Key表示multiset中的元素类型,count()函数用于统计multiset中元素值为key的元素个数,并返回其出现次数。

count()函数的使用

下面是count()函数的一个简单例子:

#include <iostream>
#include <set>

using namespace std;

int main()
{
    multiset<int> ms{10, 20, 30, 20, 40, 50};

    int val = 20;
    int cnt = ms.count(val);

    cout << "value " << val << " appears " << cnt << " times in the multiset." << endl;

    return 0;
}

输出结果为:

value 20 appears 2 times in the multiset.
count()函数的时间复杂度

count()函数的时间复杂度为O(logn),其中n为multiset中元素个数。因为multiset是基于红黑树实现的,红黑树的查找操作时间复杂度为O(logn)。

总结

multiset中的count()函数用于统计指定元素在multiset中出现的次数,使用方法非常简单。但需要注意的是,count()函数的时间复杂度比较高,如果需要频繁使用count()函数的话,建议使用unordered_multiset来代替multiset,因为unordered_multiset的查找操作时间复杂度为O(1)。