Learn C++
#include "stlalgorithms/alg_search.hpp"

Finding & Counting (find, count, all_of) in C++

//concept

Linear search algorithms answer existence questions on any range: find returns the first matching iterator (or end() when absent — always compare!), count tallies matches, and the _if variants take predicates. The quantifiers all_of/any_of/none_of collapse whole ranges to single booleans, replacing hand-written flag loops.

All are linear O(n) with early exits where possible (any_of stops at the first true). For sorted data, prefer the logarithmic binary_search family; for associative containers, prefer their member find (which beats the generic algorithm).

//how it works
1

find returns position

auto it = std::find(v.begin(), v.end(), x); — check it != v.end() before dereferencing, always.

2

Predicates with _if

find_if, count_if, remove_if take lambdas — find_if(v..., [](int x){ return x < 0; }) locates the first negative.

3

Quantifiers decide

all_of (every?), any_of (some?), none_of (clean?) turn validation loops into one readable call each.

4

Match the tool to the data

Sorted ranges deserve binary_search; maps/sets deserve member find — generic linear find is the fallback, not the default.

//example
#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
std::vector<int> v{2, 4, 6, 7};
auto it = std::find(v.begin(), v.end(), 6);
std::cout << (it != v.end()) << std::endl;
std::cout << std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) << std::endl;
std::cout << std::all_of(v.begin(), v.end(), [](int x) { return x > 0; }) << std::endl;
return 0;
}
Output
1
3
1
1find locates 6 before end(), so the presence test prints 1.
2count_if tallies evens — 2, 4, 6 qualify, 7 doesn't — printing 3.
3all_of confirms every element is positive, printing 1.
//complexity
time O(n) linear scans
space O(1)

any_of/all_of short-circuit; worst case visits every element.

//use cases
Presence checks without writing a single loop
Validation (all positive? any expired? none null?) in one call
Counting matches with predicates instead of manual tallies
Choosing member/binary variants where the data structure earns them

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.