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 < str.size(); ++i)		{			if (!isalnum(str[i]))				return true;		}		return false;	}};int main (){	vector vecstr;	vecstr.push_back("aaaaaa#aa");	vecstr.push_back("zz2zz");	vecstr.push_back("yy3yy");	int count = count_if(vecstr.begin(), vecstr.end(), FindNonAlphaNum());	cout << "The total number of non-alphanumeric strings is "endl << count << endl;// output will be 1}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS