Counting and finding
In the data we deal with daily, managing or validating the data and actively searching, locating, and quantifying specific elements or patterns within it often becomes essential. The STL equips developers with a treasure trove of precise algorithms for counting and finding.
Let’s start with the simple yet powerful std::count
and its twin std::count_if
. While std::count
can swiftly tell you how many times a specific value appears in a range, std::count_if
takes it up a notch, letting you count occurrences based on a predicate. Imagine you have a collection of student marks and wish to find out how many scored above 90. With std::count_if
, it’s a cakewalk, as shown here:
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> grades = {85, 90, 78, 92, ...