Using the count_if() Algorithm

Using the count_if() Algorithm

You can use the count_if() algorithm to count the number of elements in a container based on any condition. count_if() takes three arguments. The first and second argument areinput iterators defining the range of search within the container and the third one takes a function pointer or a function object implenting the condition based on which you want to count elements.

For instance, suppose you have a vector of strings and you want to find the total count of non-alphanumeric strings. First, you define a function object to be used as the third argument of count_if():

class FindNonAlphaNum{public:	bool operator () (const string& str)	{		for (int i = 0; i  vecstr;	vecstr.push_back("aaaaaa#aa");	vecstr.push_back("zz2zz");	vecstr.push_back("yy3yy");	int count = count_if(vecstr.begin(), vecstr.end(), FindNonAlphaNum());	cout 

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist