std::count_if() 函式在 C++ STL 中
在本文中,我們將討論 C++ STL 中 std::count_if() 函式的工作原理、語法以及示例。
什麼是 std::count_if()?
std::count_if() 函式是 C++ STL 中的一個內建函式,它在 <algorithm> 標頭檔案中定義。count_if() 用於獲取指定範圍內滿足一定條件的元素數量。此函式返回一個整數,表示滿足條件的元素數量。
此函式不僅遍歷給定的範圍,還檢查語句或條件是否為真,並計數語句或條件為真的次數,然後返回結果。
語法
count_if(start, end, condition);
引數
此函式接受以下引數 -
- start, end - 這是可用於指定我們要使用該函式的範圍的迭代器。start 給出範圍的起始位置,end 給出範圍的結束位置。
- condition - 這是我們要檢查的條件。Condition 是必須應用於給定範圍的一元函式。
返回值
此函式返回滿足條件的元素數量。
示例
輸入
bool iseve(int i){ return ((i%2)==0); }
int a = count_if( vect.begin(), vect.end(), iseve ); /* vect has 10 integers 1-10*/輸出
even numbers = 2 4 6 8 10
示例
#include <bits/stdc++.h>
using namespace std;
bool check_odd(int i){
if (i % 2!= 0)
return true;
else
return false;
}
int main() {
vector<int> vec;
for (int i = 0; i < 10; i++){
vec.push_back(i);
}
int total_odd = count_if(vec.begin(), vec.end(), check_odd);
cout<<"Number of odd is: "<<total_odd;
return 0;
}輸出
Number of odd is: 5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP