TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » Visual Basic » Algorithms
Language: C++
Expertise: Intermediate
Dec 9, 2004

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# 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

 Submit a Tip Browse "Visual Basic" Tips Browse All Tips
Thanks for your registration, follow us on our social networks to keep up-to-date