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


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

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