C++ Set 中的 count函数

首页 / C++入门教程 / C++ Set 中的 count函数

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

count - 语法

size_type count (const value_type& val) const; 

count - 参数

val :要在设置的集合中搜索的值。

count - 返回值

如果set集合中存在值val的元素,则返回1,否则返回0。

count - 例子1

让我们看一个简单的示例,使用给定的键值搜索元素:

#include <iostream>
#include <set>

using namespace std;
 
int main()
{
   //initialize container
    set<int> mp;
 
   //insert elements in random order
    mp.insert(30);
    mp.insert( 40 );
    mp.insert( 60 );
    mp.insert( 20);
    mp.insert( 50 );
 
   //checks if key 30 is present or not
    if (mp.count(30))
        cout << "The key 30 is present\n";
    else
        cout << "The key 30 is not present\n";
 
   //checks if key 100 is present or not
    if (mp.count(100))
        cout << "The key 100 is present\n";
    else
        cout << "The key 100 is not present\n";
 
    return 0;
}

输出:

The key 30 is present
The key 100 is not present

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

count - 例子2

让我们看一个简单的示例来搜索集合的元素:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<char> myset;
  char c;

  myset = {'a', 'c', 'f'};

  for (c='a'; c<'h'; c++)
  {
    cout << c;
    if (myset.count(c)>0)
      cout << " is an element of myset.\n";
    else 
      cout << " is not an element of myset.\n";
  }

  return 0;
}

输出:

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()函数用于搜索集合中的" a"至" h"元素。

count - 例子3

让我们看一个简单的示例来搜索集合中的键:

#include <iostream>
#include <set>

using namespace std;

int main(void) {

   set<char> m = {'a','b','c','d'};
            
   if (m.count('a') == 1) {
       cout<< " 'a' is present in the set \n";
   }

   if (m.count('z') == 0) {
      cout << " 'z' is not present in the set" << endl;
   }

   return 0;
}

输出:

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

在上面的示例中,键" a"出现在集合m中,因此它将是" a"的值,而键" z"不出现在集合中,因此没有值" z"。

count - 例子4

让我们看一个简单的例子:

#include <set>  
#include <iostream>  
  
int main()  
{  
    using namespace std;  
    set<int> s1;  
    set<int>::size_type i;  
  
    s1.insert(1);  
    s1.insert(1);  
  
   //Keys must be unique in set, so duplicates are ignored  
    i = s1.count(1);  
    cout << "The number of elements in s1 with a sort key of 1 is: "  
         << i << "." << endl;  
  
    i = s1.count(2);  
    cout << "The number of elements in s1 with a sort key of 2 is: "  
         << i << "." << endl;  
}

输出:

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.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

性能工程高手课 -〔庄振运〕

Service Mesh实战 -〔马若飞〕

视觉笔记入门课 -〔高伟〕

正则表达式入门课 -〔涂伟忠〕

Selenium自动化测试实战 -〔郭宏志〕

深入C语言和程序运行原理 -〔于航〕

深入浅出分布式技术原理 -〔陈现麟〕

大厂广告产品心法 -〔郭谊〕

结构执行力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)