TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C++ algorithm count_if() function

C++ algorithm count_if() function tutorial for beginners and professionals with examples on adjacent_find(),any_of(), copy(), copy_if(), count(), count_if(), equal(), find(), find_end(), find_first_of(), find_if(), find_if_not(), for_each() etc.

<< Back to CPP

C++ Algorithm Function count_if ()

C++ Algorithm count_if() function has a 'pred' value and returns the count of the elements in the range [first,last) for which the value of pred is true.

Syntax

template <class InputIterator, class UnaryPredicate>

typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last,UnaryPredicate pred);

Parameter

first: It is an input iterator to the first element in the range.

last: It is an input iterator to the last element in the range.

val: It is the element whose occurrence is being searched in the range.

Return value

The function returns the number of element in the range [first,last) for which the value of pred is true.

Example 1

#include<iostream>
#include<algorithm>
#include<vector>
bool isOdd(int k)
{
	return((k%2)==1);
}
int main()
{
	std::vector<int> newvector;
	for(int k=1; k<10; k++)
	newvector.push_back(k);
	int newcount=count_if(newvector.begin(),newvector.end(),isOdd);
	std::cout<<"newvector contains "<<newcount<<" odd values.\n";
	return 0;
}

Output:

newvector contains 5 odd values.

Example 2

#include<bits/stdc++.h>
using namespace std;
bool isEven(int k)
{
	if(k%2==0)
	return true;
}
int main()
{
	vector<int> u;
	for(int i=0; i<10; i++)
	{
		u.push_back(i);
	}
	int noEven=count_if(u.begin(),u.end(),isEven);
	cout<<"Count of even number is:"<<noEven;
	return 0;
}

Output:

Count of even number is: 10

Complexity

The complexity of the function is linear up to a distance between first and last element.

Data races

Some or all of the elements of the range are accessed

Exceptions

The function throws an exception if any of the argument throws one.






Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf