设定 C++ STL 里的 count() 函数


在本文中,我们将讨论 C++ STL 中的 set::count 函数,它们的语法、工作原理和返回的值。

什么是 C++ STL 中的 Set?

C++ STL 中的 Set 是容器,其中元素必须按照特定顺序唯一。Set 中的元素必须唯一,因为元素的值标识该元素。一旦向 set 容器中添加一个值,后期就不能再修改,不过我们仍然可以向 set 中移除或添加值。Set 被用作二叉查找树。

什么是 set::count()?

count() 函数是 C++ STL 中的内建函数,定义在头文件中。count() 用来统计 set 中关联函数的参数出现的次数。此函数只能返回两个值 0 或 1,因为在 set 中,所有值都是唯一的,因此 set 中的值最多出现一次。

语法

name_of_set.count(const type_t& value);

参数

此函数只接受 1 个参数,即我们想要在 set 容器中查找和统计的值

返回值

此函数只能返回两个值,0(值未在容器中)或 1(值在容器中)。

示例

Input: set <int> myset = {1, 2, 3, 4, 6};
   myset.count(2);
Output: 1
Input: set<int> myset = {1, 2, 3, 4, 6};
   myset.count(5);
Output: 0

示例

现场演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   int arr[] = {2, 4, 2, 5, 6, 7};
   set<int> ch(arr, arr + 6);
   // check if 2 is present
   if (ch.count(2))
   cout<<"2 is present\n";
   else
      cout<<"2 is not present\n";
   // checks if 4 is present
   if (ch.count(9))
      cout<<"9 is present\n";
   else
      cout<<"9 is not present\n";
   return 0;
}

输出

如果我们运行以上代码将生成以下输出

2 is present
9 is not present

更新日期: 05-Mar-2020

975 人浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.