C++ set count实例讲解

时间:2022-04-07
本文章向大家介绍C++ set count实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

描述

它在容器中搜索与 val 等效的元素并返回匹配的数量。

声明

以下是 std::set::count 在各种 C++ 版本中的工作方式。

C++98

size_type count (const value_type& val) const;

C++11

size_type count (const value_type& val) const;

返回值

它返回匹配的数量

异常

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

时间复杂度

时间复杂度取决于对数。

示例

下面的例子展示了 std::set::count 的用法。

#include <iostream>
#include <set>

int main () {
   std::set<int> myset;

   for (int i = 1; i < 15;++i) myset.insert(i*5);

   for (int i = 0; i < 5; ++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 not an element of myset.
4 is not an element of myset.