Engineer bro!

Sat Nov 13 2021 (2 weeks ago)

Engineer by mistake!

I am a software engineer by passion

The count() and count_if() function in C++ | STL

In this article, we'll see that how can we use count() and count_if() function to count the element in the array.

Table of contents

count()count()

The count() function returns the number of elements in the range [first,last)[first, last) satisfying specific criteria.

Demo count()

int main() {
    vector<int> v{2, 2, 4, 8};
    cout << count(v.begin(), v.end(), 2);
    return 0;
}

O/P
2

count_if()

count_if function returns the number of element for which predicates p returned true for the range [first,last)[first, last).

count_if demo

Count the number of elements which are divisible by 2

int main() {
    vector<int> v{2, 2, 4, 8};
    cout << count_if(v.begin(), v.end(), [](int a) { return a % 2 == 0; });
    return 0;
}

O/P
4

References

Thank You ❤️

cpstlcountcount_ifcpp

Comments (0)

Discussions (0)


© 2021 dsabyte. All rights reserved