設定 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP