algorithm - STL C++

count_if()

Declaration

template <class InputIterator, class Predicate>
InputIterator::difference_type count_if(
	InputIterator qFirst,
	InputIterator qLast,
	Predicate xPred
);

Description

This function counts the number of entries that satisfy "xPred" and that are in the range from "qFirst" up to the entry before "qLast."

Header Include

#include <algorithm>

Example

#include <iostream>
#include <vector>
#include <algorithm>

// Test function
bool LessThanI(char cChar) {
	return (cChar < 'i');
}

int main()
{
	using namespace std;

	// Create a vector instance
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char>::iterator qIter;
	// Output the vector
	cout << "V: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Count the chars less than 'i' and output the number
	vector<char>::iterator::difference_type qCount;
	qCount = count_if(qV.begin(), qV.end(), LessThanI);
	cout << "There are " << qCount << " characters less than \'i\' in V." << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

count_if() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.