Finding & Counting (find, count, all_of) in C++
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).
find returns position
auto it = std::find(v.begin(), v.end(), x); — check it != v.end() before dereferencing, always.
Predicates with _if
find_if, count_if, remove_if take lambdas — find_if(v..., [](int x){ return x < 0; }) locates the first negative.
Quantifiers decide
all_of (every?), any_of (some?), none_of (clean?) turn validation loops into one readable call each.
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.
#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;}any_of/all_of short-circuit; worst case visits every element.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.