
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
count_if() in C++ STL
In this article we will be discussing the working, syntax and examples of std::count_if() function in C++ STL.
What is std::count_if()?
std::count_if() function is an inbuilt function in C++ STL, which is defined in <algorithm> header file. count_if() is used to get the number of elements in a specified range which satisfy a condition. This function returns an integer value which is the number of elements which satisfies the condition.
The function not only iterates through the given range but also checks if the statement or condition is true and counts how many times the statement or condition was true and returns the result.
Syntax
count_if(start, end, condition);
Parameters
The function accepts the following parameter(s) −
- start, end − These are the iterators which can be used to give a range in which we have to use the function. start gives the beginning position of the range and end gives the ending position of the range.
- condition − This is the condition which we want to check. Condition is the unary function which has to be applied on the given range.
Return value
This function returns the number of elements which are meeting the condition.
Example
Input
bool iseve(int i){ return ((i%2)==0); } int a = count_if( vect.begin(), vect.end(), iseve ); /* vect has 10 integers 1-10*/
Output
even numbers = 2 4 6 8 10
Example
#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; }
Output
Number of odd is: 5
- Related Articles
- multimap::count() in C++ STL
- Set count() function in C++ STL
- multiset count() function in C++ STL
- Count smaller elements on right side using Set in C++ STL
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Program to check if an Array is Palindrome or not using STL in C++
- Containers in C++ STL
- Library in C++ STL?
- stable_sort() in C++ STL
- deque_resize( ) in C++ in STL
- deque_rbegin( ) in C++ in STL
- deque_rend( ) in C++ in STL
- deque_insert( ) in C++ in STL
- deque_emplace in C++ in STL
- deque_crend in C++ in STL

Advertisements