Algorithms in the STL (C++)
Algorithms in Header <algorithm>
(From https://cplusplus.com/reference/algorithm/)
The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements.
A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of some of the STL containers. Notice though, that algorithms operate through iterators directly on the values, not affecting in any way the structure of any possible container (it never affects the size or storage allocation of the container).
Non-modifying sequence operations
all_of | Test condition on all elements in range (function template) |
any_of | Test if any element in range fulfills condition (function template) |
none_of | Test if no elements fulfill condition (function template) |
for_each | Apply function to range (function template) |
find | Find value in range (function template). See also search |
find_if(first, last, unaryPred) | Find element in range that fulfills unaryPred (function template) |
find_if_not | Find element in range (negative condition) (function template) |
find_end | Find last subsequence in range (function template) |
find_first_of | Find element from set in range (function template) |
adjacent_find | Find equal adjacent elements in range (function template) |
count |
Count appearances of value in range (function template) |
count_if | Return number of elements in range satisfying condition (function template) |
mismatch | Return first position where two ranges differ (function template) |
equal | Test whether the elements in two ranges are equal (function template) |
is_permutation | Test whether range is permutation of another (function template) |
search | Search range for subsequence (function template) |
search_n | Search range for elements (function template) |
all_of
template <class InItor, class UnaryPredicate> bool all_of (InItor first, InItor last, UnaryPredicate pred);
Returns true if pred returns true for all the elements in the range [first,last) or if the range is empty, and false otherwise.
An example:
// all_of example
#include <iostream> // std::cout
#include <algorithm> // std::all_of
#include <array> // std::array
int main () {
std::array<int,8> foo = {3,5,7,11,13,17,19,23};
if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
std::cout << "All the elements are odd numbers.\n";
return 0;
}
Output:
All the elements are odd numbers.
for_each
template <class InItor, class Function> Function for_each (InItor first, InItor last, Function fn);
Applies function fn to each of the elements in the range [first,last), where fn is a unary function that accepts an element in the range as argument. This can either be a function pointer or a move constructible function object. Its return value, if any, is ignored.
An example:
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
void myfunction (int i) { // function:
std::cout << ' ' << i;
}
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
} myobject;
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
std::cout << '\n';
// or:
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
std::cout << '\n';
return 0;
}
Output:
myvector contains: 10 20 30 myvector contains: 10 20 30
find
template <class InItor, class T> InItor find (InItor first, InItor last, const T& val);
Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.
The function uses operator== to compare the individual elements to val.
See also search
search
template <class FwdItor1, class FwdItor2> FwdItor1 search (FwdItor1 first1, FwdItor1 last1, FwdItor2 first2, FwdItor2 last2); template <class FwdItor1, class FwdItor2, class BinPred> FwdItor1 search (FwdItor1 first1, FwdItor1 last1, FwdItor2 first2, FwdItor2 last2, BinPred pred);
Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found.
The elements in both ranges are compared sequentially using operator== (or pred, in the second version: A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2).
This function returns the first of such occurrences. For an algorithm that returns the last instead, see find_end.
An example:
// search algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::search
#include <vector> // std::vector
bool mypredicate (int i, int j) {
return (i==j);
}
int main () {
std::vector<int> haystack;
// set some values: haystack: 10 20 30 40 50 60 70 80 90
for (int i=1; i<10; i++) haystack.push_back(i*10);
// using default comparison:
int needle1[] = {40,50,60,70};
std::vector<int>::iterator it;
it = std::search (haystack.begin(), haystack.end(), needle1, needle1+4);
if (it!=haystack.end())
std::cout << "needle1 found at position " << (it-haystack.begin()) << '\n';
else
std::cout << "needle1 not found\n";
// using predicate comparison:
int needle2[] = {20,30,50};
it = std::search (haystack.begin(), haystack.end(), needle2, needle2+3, mypredicate);
if (it!=haystack.end())
std::cout << "needle2 found at position " << (it-haystack.begin()) << '\n';
else
std::cout << "needle2 not found\n";
return 0;
}
Output:
needle1 found at position 3 needle2 not found
find_end
template <class FwdItor1, class FwdItor2> FwdItor1 find_end (FwdItor1 first1, FwdItor1 last1, FwdItor2 first2, FwdItor2 last2); template <class FwdItor1, class FwdItor2, class BinPred> FwdItor1 find_end (FwdItor1 first1, FwdItor1 last1, FwdItor2 first2, FwdItor2 last2, BinPred pred);
Searches the range [first1,last1) for the last occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found.
The elements in both ranges are compared sequentially using operator== (or pred, in the second version): A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2).
This function returns the last of such occurrences. For an algorithm that returns the first instead, see search.
find_first_of
template <class InItor, class FwdItor> InItor find_first_of (InItor first1, InItor last1, FwdItor first2, FwdItor last2); template <class InItor, class FwdItor, class BinPred> InItor find_first_of (InItor first1, InItor last1, FwdItor first2, FwdItor last2, BinPred pred);
Returns an iterator to the first element in the range [first1,last1) that matches any of the elements in [first2,last2). If no such element is found, the function returns last1.
The elements in [first1,last1) are sequentially compared to each of the values in [first2,last2) using operator== (or pred, in the second version), until a pair matches.
adjacent_find
template <class FwdItor> FwdItor adjacent_find (FwdItor first, FwdItor last); template <class FwdItor, class BinPred> FwdItor adjacent_find (FwdItor first, FwdItor last, BinPred pred);
Searches the range [first,last) for the first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. Two elements match if they compare equal using operator== (or using pred, in version two)
Modifying sequence operations
copy | Copy range of elements (function template) |
copy_n | Copy elements (function template) |
copy_if | Copy certain elements of range (function template) |
copy_backward | Copy range of elements backward (function template) |
move | Move range of elements (function template) |
move_backward | Move range of elements backward (function template) |
swap | Exchange values of two objects (function template) |
swap_ranges | Exchange values of two ranges (function template) |
iter_swap | Exchange values of objects pointed to by two iterators (function template) |
transform | Transform range (function template) |
replace | Replace value in range (function template) |
replace_if | Replace values in range (function template) |
replace_copy | Copy range replacing value (function template) |
replace_copy_if | Copy range replacing value (function template) |
fill | Fill range with value (function template) |
fill_n | Fill sequence with value (function template) |
generate | Generate values for range with function (function template) |
generate_n | Generate values for sequence with function (function template) |
remove | Remove value from range (function template) |
remove_if | Remove elements from range (function template) |
remove_copy | Copy range removing value (function template) |
remove_copy_if | Copy range removing values (function template) |
unique | Remove consecutive duplicates in range (function template) |
unique_copy | Copy range removing duplicates (function template) |
reverse | Reverse range (function template) |
reverse_copy | Copy range reversed (function template) |
rotate | Rotate left the elements in range (function template) |
rotate_copy | Copy range rotated left (function template) |
random_shuffle | Randomly rearrange elements in range (function template) |
shuffle | Randomly rearrange elements in range using generator (function template) |
Partitions
is_partitioned | Test whether range is partitioned (function template) |
partition | Partition range in two (function template) |
stable_partition | Partition range in two - stable ordering (function template) |
partition_copy | Partition range into two (function template) |
partition_point | Get partition point (function template) |
Sorting
sort | Sort elements in range (function template) |
stable_sort | Sort elements preserving order of equivalents (function template) |
partial_sort | Partially sort elements in range (function template) |
partial_sort_copy | Copy and partially sort range (function template) |
is_sorted | Check whether range is sorted (function template) |
is_sorted_until | Find first unsorted element in range (function template) |
nth_element | Sort element in range (function template) |
Binary search (operating on partitioned/sorted ranges)
lower_bound | Return iterator to lower bound (function template) |
upper_bound | Return iterator to upper bound (function template) |
equal_range | Get subrange of equal elements (function template) |
binary_search | Test if value exists in sorted sequence (function template) |
Merge (operating on sorted ranges)
merge | Merge sorted ranges (function template) |
inplace_merge | Merge consecutive sorted ranges (function template) |
includes | Test whether sorted range includes another sorted range (function template) |
set_union | Union of two sorted ranges (function template) |
set_intersection | Intersection of two sorted ranges (function template) |
set_difference | Difference of two sorted ranges (function template) |
set_symmetric_difference | Symmetric difference of two sorted ranges (function template) |
Heap
push_heap | Push element into heap range (function template) |
pop_heap | Pop element from heap range (function template) |
make_heap | Make heap from range (function template) |
sort_heap | Sort elements of heap (function template) |
is_heap | Test if range is heap (function template) |
is_heap_until | Find first element not in heap order (function template) |
Min/max
min | Return the smallest (function template) |
max | Return the largest (function template) |
minmax | Return smallest and largest elements (function template) |
min_element | Return smallest element in range (function template) |
max_element | Return largest element in range (function template) |
minmax_element | Return smallest and largest elements in range (function template) |
Other
lexicographical_compare | Lexicographical less-than comparison (function template) |
next_permutation | Transform range to next permutation (function template) |
prev_permutation | Transform range to previous permutation (function template) |