C++ Algorithm library by examples
- all_of, any_of, none_of
- E.g. Check if all value in vector is positive.
vector<int> v{1, 2, 3};
bool allPositive = all_of(begin(v), end(v), [](int x) { return x > 0; });
- for_each, for_each_n
- E.g. Iterate on value in vector, and can modify them.
vector<int> v{1, 2, 3};
// add 1 to every element
for_each(begin(v), end(v), [](int &x) { x++; });
for_each_n(begin(v), 3, [](int &x) { x++; });
- count, count_if
- E.g. Count positive value in vector.
vector<int> v{1, 2, 3};
int target = 3;
int numOf3 = count(begin(v), end(v), target);
int numOfPositive = count_if(begin(v), end(v), [](int x) {return x > 0; });
- mismatch
- E.g. Compare two vector, return first different value pair.
vector<int> v1{1, 2, 3};
vector<int> v2{1, 3, 3};
// Return first non-identical iterators
auto [it1, it2] = mismatch(begin(v1), end(v1), begin(v2));
auto [it1, it2] = mismatch(begin(v1), end(v1), begin(v2), [](int x, int y) { return x == y; });
- find, find_if, find_if_not
- E.g. Find first non-positive value;
vector<int> v{1, 2, 3};
auto it = find_if_not(begin(v), end(v), [](int x) { return x > 0; });
- find_end
- E.g.
- find_first_of
// Given a range and target array, find first element in range has element in target array
find_first_of(begin(v), end(v), )
- search
// Find if some seq is in other seq
const std::boyer_moore_searcher searcher(begin(sub), end(sub));
search(begin(target), end(target), searcher);