dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Intermediate
Dec 9, 2004

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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<string> 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
}
Saurabh Ramya
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date