The <algorithm> header declares the generic algorithm functions for operating on containers and similar objects. Refer to Chapter 11, Containers and Algorithms, for more information about using and writing generic algorithms.
This section uses a number of abbreviations and conventions. Each algorithm is described first using plain English. Under the Technical details heading is a more mathematical description of the algorithm, which tends to be harder to read.
The names of the template parameters tell you what kind of iterator is expected. The iterator kind is the minimal functionality needed, so you can, for example, use a random access iterator where at least a forward iterator is needed. To keep the syntax summaries short and readable, the iterator kinds are abbreviated, as shown in Table 13-1.
Parameter name | Iterator kind |
---|---|
BidiIter |
Bidirectional iterator |
FwdIter |
Forward iterator |
InIter |
Input iterator |
OutIter |
Output iterator |
RandIter |
Random access iterator |
Other template parameter names are chosen to be self-explanatory. For example, any name that ends in Predicate is a function that returns a Boolean result (which can be type bool
or any other type that is convertible to bool
) or a functional object that declared a function call operator that returns a Boolean result.
In the Technical details part of each description, the following notation is used:
template<typename FwdIter> FwdIter adjacent_find(FwdIter first, FwdIter last); template<typename FwdIter, typename BinaryPredicate> FwdIter adjacent_find(FwdIter first, FwdIter last, BinaryPredicate pred);
The adjacent_find
function template looks for adjacent items in the range [first
, last
) that are equal (first version) or where pred(item1,
item2)
is true (second version). Items are "adjacent" when their iterators differ by one position (e.g., ++iter1
==
iter2
).
The return value is an iterator that points to the first of the adjacent items, or last
if no matching items are found. See Figure 13-1 for an example.
Figure 13-1: Example for adjacent_find
Returns i where i = first + n and n is the smallest value where *(first + n) == *(first + n + 1) and first + n < last, or if there is no such n, i = last.
Complexity is linear: the standard is muddled, but any reasonable implemention will call the predicate (operator==
or pred
) exactly n + 1 times.
find function template, find_if function template
template<typename FwdIter, typename T> bool binary_search(FwdIter first, FwdIter last, const T& value); template<typename FwdIter, typename T, typename Compare> bool binary_search(FwdIter first, FwdIter last, const T& value, Compare comp);
The binary_search
function template uses binary search to test whether value
is in the range [first
, last
). It returns true for success and false if the value is not found.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
The contents in the range must be sorted.
Precondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Returns true if there is an i in [first, last) such that !(*i < value) and !(value < *i); returns false if there is no such i.
Complexity is logarithmic in the number of comparisons, which is at most log(last - first) + 2. Although the iterator can be a forward iterator, the best performance is obtained with a random access iterator. With a forward or bidirectional iterator, a linear number of steps is required (even though the number of comparisons is still logarithmic).
equal_range function template, find function template, find_if function template, lower_bound function template, upper_bound function template
template<typename InIter, typename OutIter> OutIter copy(InIter first, IntIter last, OutIter result);
The copy
function template copies items from [first
, last
) to the output iterator starting at result
. You must ensure the output container has enough room for last
-
first
items.
The result
cannot be in the source range [first
, last
), but other parts of the destination can overlap with the source.
The return value is the value of the result
iterator after copying all the items, as shown in Figure 13-2.
Figure 13-2: Example of copy
See Example 13-2 (under generate
) for a code example.
Assigns *(result + n) = *(first + n) for all n in the range [0, (last - first)).
Complexity is linear: exactly last - first assignments are performed.
copy_backward function template, partial_sort_copy function template, replace_copy function template, remove_copy function template, reverse_copy function template, rotate_copy function template, unique_copy function template
template<typename BidiIter1, typename BidiIter2> BidiIter2 copy_backward(BidiIter1 first, BidiIter1 last, BidiIter2 result);
The copy_backward
function template does the same thing as copy
, but it works backwards, starting at the element before last
and copying elements towards first
. The result
iterator points to one past the end of the destination, and is decremented before copying each element.
The result
cannot be in the source range [first
, last
), but other parts of the destination can overlap with the source.
The return value is an iterator that points to the first element of the destination, as shown in Figure 13-3.
Figure 13-3: Example of copy_backward
Assigns *(result - n) = *(last - n) for all n in the range [1, (last - first)].
Complexity is linear: exactly last - first assignments are performed.
copy function template
template<typename InIter, typename T> typename iterator_traits<InIter>::difference_type count(InIter first, InIter last, const T& value);
The count
function template returns the number of elements in the range [first
, last
) that are equal to value
.
Complexity is linear: exactly last - first comparisons are performed.
count_if function template
template<typename InIter, typename Predicate> typename iterator_traits<InIter>::difference_type count_if(InIter first, InIter last, Predicate pred);
The count_if()
function template returns the number of elements in the range [first
, last
) where pred(*iter)
returns true.
Complexity is linear: pred
is called exactly last - first times.
count function template, find_if function template
template<typename InIter1, typename InIter2> bool equal(InIter1 first1, InIter1 last1, InIter2 first2); template<typename InIter1, typename InIter2, typename BinaryPredicate> bool equal(InIter1 first1, InIter1 last1, InIter2 first2, BinaryPredicate pred);
The equal
function template returns true if two ranges contain the same elements in the same order. The first range is [first1
, last1
), and the second range has the same number of elements, starting at first2
. The ranges can overlap.
The first form compares items using the ==
operator. The second form calls pred(*iter1,
*iter2)
.
Returns true if *(first1 + n) == *(first2 + n) for all n in the range [0, (last1 - first1)).
Complexity is linear: at most last1 - first1 comparisons are performed.
lexicographical_compare function template, mismatch function template, search function template
template<typename FwdIter, typename T> pair<FwdIter, FwdIter> equal_range(FwdIter first, FwdIter last, const T& value); template<typename FwdIter, typename T, typename Compare> pair<FwdIter, FwdIter> equal_range(FwdIter first, FwdIter last, const T& value, Compare comp);
The equal_range
function template determines where value
belongs in the sorted range [first
, last
). It returns a pair of iterators that specify the lower bound and upper bound of where you can insert value
and preserve the sorted nature of the range.
The first form compares values using the <
operator; the second form calls comp(*iter
, value)
.
Figure 13-4 shows an example of finding the bounds for the value 36. The result of calling equal_range
is pair(lb,
ub)
. Note that for values in the range [19, 35], lb
is the upper and lower bound, and for values in the range [37, 41], ub
is the upper and lower bound.
Figure 13-4: Example of equal_range, lower_bound, and upper_bound of 36
Precondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Returns the equivalent of calling the following, although the actual implementation might be different:
std::make_pair(std::lower_bound(first, last, value), std::upper_bound(first, last, value))
or
std::make_pair(std::lower_bound(first, last, value, comp), std::upper_bound(first, last, value, comp))
Complexity is logarithmic in the number of comparisons, which is at most 2 × log(last - first) + 1. Although the iterator can be a forward iterator, the best performance is obtained with a random access iterator. With a forward or bidirectional iterator, a linear number of steps is required (even though the number of comparisons is still logarithmic).
binary_search function template, lower_bound function template, pair template class, upper_bound function template
template<typename FwdIter, typename T> void fill(FwdIter first, FwdIter last, const T& value);
The fill
function template fills the destination range [first
, last
) by assigning value
to each item in the range.
Assigns *i = value for all i in the range [first, last).
Complexity is linear: exactly last - first assignments are performed.
fill_n function template, generate function template
template<typename OutIter, typename Size, typename T> void fill_n(OutIter first, Size n, const T& value);
The fill_n
function template assigns value
to successive items in the destination range, starting at first
, and assigning exactly n
items.
The Size
template parameter must be convertible to an integral type.
Assigns *(first + n) = value for all n in the range [0, n).
Complexity is linear: exactly n assignments are performed.
fill function template, generate_n function template
template<typename InIter, typename T> InIter find(InIter first, InIter last, const T& value);
The find
function template returns an iterator that points to the first occurrence of value
in [first
, last
). It returns last
if value is not found. The ==
operator compares items.
Returns i = first + n, where n is the smallest value such that *(first + n) == value. If there is not such n, i = last.
Complexity is linear: at most last - first comparisons are performed.
find_end function template, find_first function template, find_if function template, search function template
template<typename FwdIter1, typename FwdIter2> FwdIter1 find_end(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2); template<typename FwdIter1, typename FwdIter2, typename BinaryPredicate> FwdIter1 find_end(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2, BinaryPredicate pred);
The find_end
function template finds the last (rightmost) subsequence [first2
, last2
) within the range [first1
, last1
), as illustrated in Figure 13-5. It returns last1
if the subsequence is not found.
The first form compares items with the ==
operator; the second form calls pred(*iter1,
*iter2)
.
Figure 13-5: Example of find_end and search
Let length1 = last1 - first1 and length2 = last2 - first2.
Returns first1 + n where n is the highest value in the range [0, length1 - length2) such that *(i + n + m) == (first2 + m) for all m in the range [0, length2). Returns last1 if no such n can be found.
Complexity is quadratic: at most length1 × length2 comparisons are performed.
find function template, search function template
template<typename FwdIter1, typename FwdIter2> FwdIter1 find_first_of(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2); template<typename FwdIter1, typename FwdIter2, typename BinaryPredicate> FwdIter1 find_first_of(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2, BinaryPredicate pred);
The find_first_of
function template searches the range [first1
, last1
) for any one of the items in [first2
, last2
). If it finds one, it returns an iterator that points in the range [first1
, last1
) for the matching item. It returns last1
if no matching item is found. Figure 13-6 shows an example.
The first form compares items with the ==
operator; the second form calls pred(*iter1,
*iter2)
.
Figure 13-6: Example of find_first_of
Let length1 = last1 - first1 and length2 = last2 - first2.
Returns first1 + n where n is the smallest value in the range [0, length1) such that *(first1 + n) == (first2 + m) for some m in the range [0, length2). Returns last1 if no such n and m can be found.
Complexity is quadratic: at most length1 × length2 comparisons are performed.
find function template
template<typename InIter, typename Predicate> InIter find_if(InIter first, InIter last, Predicate pred);
The find_if
function template, similar to find, searches the range [first
, last
) for the first item for which pred(*iter)
is true. If no matching item is found, last
is returned.
Returns i = first + n, where n is the smallest value such that pred(*(first + n), value) != false. If there is not such n, i = last.
Complexity is linear: pred
is called at most last - first times.
find function template
template<typename InIter, typename Function> Function for_each(InIter first, InIter last, Function f);
The for_each
function template calls f
for each item in the range [first
, last
), passing the item as the sole argument to f
. It returns f
.
Example 13-1 shows a use of for_each
that tests whether a sequence is sorted. The is_sorted
object remembers the previous item in the sequence, which is compares with the current item. The overloaded bool
operator returns true if the sequence is sorted or false if the sequence is out of order. The example takes advantage of the fact that for_each
returns the f parameter as its result.
Example 13-1: Using for_each to test whether a list is sorted
#include <iostream> #include <algorithm> #include <list> template<typename T> class is_sorted { public: is_sorted() : first_time(true), sorted(true) {} void operator()(const T& item) { // for_each calls operator() for each item if (first_time) first_time = false; else if (item < prev_item) sorted = false; prev_item = item; } operator bool() { return sorted; } private: bool first_time; bool sorted; T prev_item; }; int main() { std::list<int> l; l.push_back(10); l.push_back(20); ... if (std::for_each(l.begin(), l.end(), is_sorted<int>())) std::cout << "list is sorted" << std::endl; }
Complexity is linear: f
is called exactly last - first times.
accumulate function template, copy function template, ostream_iterator function template
template<typename FwdIter, typename Generator> void generate(FwdIter first, FwdIter last, Generator gen);
The generate
function template fills the sequence [first
, last
) by assigning the result of calling gen()
repeatedly.
Example 13-2 shows a simple way to fill a sequence with successive integers.
Example 13-2: Using generate to fill a vector with integers
#include <algorithm> #include <iostream> #include <iterator> #include <vector> // Generate a series of objects, starting with "start". // Use the ++ operator for successive values. template <typename T> class series { public: series(const T& start) : next(start) {} T operator()() { return next++; } private: T next; }; int main() { std::vector<int> v; v.resize(10); // Generate integers from 1 to 10. std::generate(v.begin(), v.end(), series<int>(1)); // Print the integers, one per line. std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); }
Complexity is linear: gen
is called exactly last - first times.
fill function template, generate_n function template
template<typename OutIter, typename Size, typename Generator> void generate_n(OutIter first, Size n, Generator gen);
The generate_n
function template calls gen()
exactly n
times, assigning the results to fill the squence that starts at first
. You must ensure that the sequence has room for at least n
items. The Size
type must be convertible to an integral type.
Example 13-3 shows a simple way to print a sequence of integers.
Example 13-3: Using generate_n to print a series of integers
#include <algorithm> #include <iostream> #include <iterator> // Use the same series template from Example 13-2. int main() { // Print integers from 1 to 10. std::generate_n(std::ostream_iterator<int>(std::cout,"\n"), 10, series<int>(1)); }
Complexity is linear: gen
is called exactly n times.
fill_n function template , generate function template
template<typename InIter1, typename InIter2> bool includes(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2); template<typename InIter1, typename InIter2, typename Compare> bool includes(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, Compare comp);
The includes
function template checks for a subset relationship, that is, it returns true if every element in the sorted sequence [first2
, last2
) is contained in the sorted sequence [first1
, last1
). It returns false otherwise.
Both sequences must be sorted. The first form uses the <
operator to order the elements. The second form calls comp(*iter1
, *iter2)
.
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Returns true if there is an i in [first1, last1) such that *(i + n) = *(first2 + n) for all n in [0, (last2 - first2)). Returns last1 if there is no such i.
Complexity is linear: at most 2 × ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed.
set_difference function template, set_intersection function template, set_symmetric_difference function template, set_union function template
template<typename BidiIter> void inplace_merge(BidiIter first, BidiIter middle, BidiIter last); template<typename BidiIter, typename Compare> void inplace_merge(BidiIter first, BidiIter middle, BidiIter last, Compare comp);
The inplace_merge
function template merges two sorted, consecutive ranges int place, creating a single sorted range. The two ranges are [first
, middle
) and [middle
, last
). The resulting range is [first
, last
).
The merge is stable, so elements retain their respective orders, with equivalent elements in the first range coming before elements in the second.
Both sequences must be sorted. The first form uses the <
operator to compare elements. The second form calls comp(*iter1
, *iter2)
.
Figure 13-7 depicts the operation of inplace_merge
.
Figure 13-7: Example of inplace_merge
Precondition: !(*(i - 1) < *i) for all i in [first, middle - 1) and !(*(j - 1) < *j) for all j in [middle, last - 1).
Postcondition: !(*(i - 1) < *i) for all i in [first, last - 1).
The performance is usually linear with n + 1 comparisons, but if enough temporary memory is not available, the performance might be n log n, where n is last - first.
merge function template, sort function template
template<typename FwdIter1, typename FwdIter2> void iter_swap(FwdIter1 a, FwdIter2 b);
The iter_swap
function template swaps the values pointed to by a
and b
. That is, you can think of its functionality as follows:
FdwIter1::value_type tmp = b*; *b = *a; *a = tmp;
Performance: constant.
copy function template, swap function template, swap_ranges function template
template<typename InIter1, typename InIter2> bool lexicographical_compare(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2); template<typename InIter1, typename InIter2, typename Compare> bool lexicographical_compare(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, Compare comp);
The lexicographical_compare
function template returns true if the sequence [first1
, last1
) is less than the sequence [first2
, last2
). If the sequences have the same length and contents, the return value is false. If the second sequence is a prefix of the first, true is returned.
The first form uses the <
operator to compare elements. The second form calls comp(*iter1
, *iter2)
.
Let length1 = last1 - first1, length2 = last2 - first2, and minlength = min(length1, length2).
Returns true if either of the following conditions is true:
Complexity is linear: at most minlength comparisons are performed.
equal function template
template<typename FwdIter, typename T> FwdIter lower_bound(FwdIter first, FwdIter last, const T& value); template<typename FwdIter, typename T, typename Compare> FwdIter lower_bound(FwdIter first, FwdIter last, const T& value, Compare comp);
The lower_bound
function template determines where value
belongs in the sorted range [first
, last
). It returns an iterator that points to the first (leftmost) position where you can insert value
and preserve the sorted nature of the range.
The first form compares values using the <
operator; the second form calls comp(*iter
, value)
.
Figure 13-4 (under equal_range
) shows an example of finding the bounds for the value 36. Note that for values in the range [19, 35], lb
is the lower bound, and for values in the range [37, 41], ub
is the lower bound.
Precondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Returns first + n where n is the highest value in [0, last - first) such that *(first + m) < value for all m in [0, n).
Complexity is logarithmic in the number of comparisons, which is at most log(last - first) + 1. Although the iterator can be a forward iterator, the best performance is obtained with a random access iterator. With a forward or bidirectional iterator, a linear number of steps is required (even though the number of comparisons is still logarithmic).
binary_search function template, equal_range function template, upper_bound function template
template<typename RandIter> void make_heap(RandIter first, RandIter last); template<typename RandIter, typename Compare> void make_heap(RandIter first, RandIter last, Compare comp);
The make_heap
function template reorders the elements in the range [first
, last
) to form a heap in place.
The first form compares values using the <
operator; the second form calls comp(*iter
, value)
.
A heap is a data structure that is ideally suited for implementing priority queues. C++ defines a range as a heap if two properties are satisfied:
The classic description of a heap is as a binary tree, where each node is greater than or equal to its children, but the relative order of the children is not specified. Thus, the root of the tree is the largest element in the entire tree.
Although it is simplest to think of a heap as a binary tree, a heap is typically implemented with an array, where the children for the node at index i can be found at 2i and 2i + 1, which means the parent for the node at index i is at i / 2. The root is at index 1.
Postcondition: [first, last) is a heap.
Complexity is linear: at most 3 × (last - first) comparisons are performed.
priority_queue template class, pop_heap function template, push_heap function template, sort_heap function template
template<typename T> const T& max(const T& a, const T& b); template<typename T, typename Compare> const T& max(const T& a, const T& b, Compare comp);
The max
function template returns the larger of a
and b
. If neither one is larger, it returns a
.
The first form compares values using the <
operator; the second form calls comp(a
, b)
.
max_element function template, min function template
template<typename FwdIter> FwdIter max_element(FwdIter first, FwdIter last); template<typename FwdIter, typename Compare> FwdIter max_element(FwdIter first, FwdIter last, Compare comp);
The max_element
function template returns an iterator that points to the largest element in the range [first
, last
). If there are multiple instances of the largest element, the iterator points to the first such instance.
The first form compares values using the <
operator; the second form calls comp(*iter1
, *iter2)
.
Returns first + n where n is the smallest value in [0, last - first) such that for all m in [0, last - first), *(first + n) < *(first + m) is false.
Complexity is linear: exactly max(last - first - 1, 0) comparisons are performed.
max function template, min_element function template
template<typename InIter1, typename InIter2, typename OutIter> OutIter merge(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result); template<typename InIter1, typename InIter2, typename OutIter, typename Compare> OutIter merge(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result, Compare comp);
The merge
function template merges the sorted ranges [first1
, last1
) and [first2
, last2
), copying the results into the sequence that starts with result
. You must ensure the destination has enough room for the entire merged sequence.
The return value is the end value of the destination iterator, that is, result
+ (last1
- first1
) + (last2
- first2
).
The destination range must not overlap either of the input ranges.
The merge is stable, so elements preserve their relative order. Equivalent elements are copied so elements from the first range come before elements from the second range.
The first form compares values using the <
operator; the second form calls comp(*iter1
, *iter2)
.
Let length1 = last1 - first 1, and length2 = last2 - first2.
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Postcondition: !(*(i - 1) < *i) for all i in [result, result + length1 + length2)
Complexity is linear: at most length1 + length2 - 1 comparisons are performed.
inplace_merge function template, sort function template
template<typename T> const T& min(const T& a, const T& b); template<typename T, typename Compare> const T& min(const T& a, const T& b, Compare comp);
The min
function template returns the smaller of a
and b
. If neither one is smaller, it returns a
.
The first form compares values using the <
operator; the second form calls comp(a
, b)
.
max function template, min_element function template
template<typename FwdIter> FwdIter min_element(FwdIter first, FwdIter last); template<typename FwdIter, typename Compare> FwdIter min_element(FwdIter first, FwdIter last, Compare comp);
The min_element
function template returns an iterator that points to the smallest element in the range [first
, last
). If there are multiple instances of the smallest element, the iterator points to the first such instance.
The first form compares values using the <
operator; the second form calls comp(*iter1
, *iter2)
.
Returns first + n where n is the smallest value in [0, last - first) such that for all m in [0, last - first), *(first + m) < *(first + n) is false.
Complexity is linear: exactly max(last - first - 1, 0) comparisons are performed.
max_element function template, min function template
template<typename InIter1, typename InIter2> pair<InIter1, InIter2> mismatch(InIter1 first1, InIter1 last1, InIter2 first2); template<typename InIter1, typename InIter2, typename BinaryPredicate> pair<InIter1, InIter2> mismatch(InIter1 first1, InIter1 last1, InIter2 first2, BinaryPredicate pred);
The mismatch
function template compares two sequences pairwise, and returns a pair of iterators that identifies the first elements where the sequences differ. The first sequence is [first1
, last1
), and the second sequence starts at first2
and has at least as many elements as the first sequence.
The return value is a pair of iterators; the first member of the pair points to the first sequence and second points to the second. The two iterators have the same offset within the respective ranges. If the two sequences are equivalent, the pair returned is last1
and an iterator that points to the second sequence at the same offset (call it last2
).
The first form compares items with the ==
operator; the second form calls pred(*iter1,
*iter2)
.
Figure 13-8 illustrates how the mismatch
function template works.
Figure 13-8: Example of mismatch
Returns the pair (first1 + n, first2 + n) where n is the smallest value in [0, last1 - first1) such that *(first1 + n) == *(first2 + n) is false and *(first1 + m) == *(first2 + m) is true for all m in [0, n). If there is no such n, n == last1 - first1.
Complexity is linear: at most last1 - first1 comparisons are performed.
equal function template, search function template
template<typename BidiIter> bool next_permutation(BidiIter first, BidiIter last); template<typename BidiIter, typename Compare> bool next_permutation(BidiIter first, BidiIter last, Compare comp);
The next_permutation
function template rearranges the contents of the range [first
, last
) to the next permutation, assuming a set of lexicographically ordered permutations. The return value is true for generating the next permutation, or false if there are no more permutations, in which case the first permutation is generated (that is, with all elements in lexicographically ascending order).
Figure 13-9 depicts all the permutations, in order, for a sequence. The next_permutation
function swaps elements to form the next permutation. For example, if the input is permutation 2, the result is permutation 3. If the input is permutation 6, the result is 1, and next_permutation
returns false.
Figure 13-9: Permutations of a sequence
Example 13-4 shows a simple program that prints all the permutations of a sequence of integers. You can use this program to better understand the next_permutation
function template.
Example 13-4: Generating permutations
#include <algorithm> #include <iostream> #include <iterator> #include <vector> void print(const std::vector<int>& v) { std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } int main() { std::vector<int> v; std::cout << "Enter a few integers, followed by EOF:"; std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_insert_iterator<std::vector<int> >(v)); // Start with the first permutation (ascending order). std::sort(v.begin(), v.end()); print(v); // Print all the subsequent permutations. while (std::next_permutation(v.begin(), v.end())) print(v); }
Complexity is linear: at most (last - first) / 2 swaps.
lexicographical_compare function template, prev_permutation function template, swap function template
template<typename RandIter> void nth_element(RandIter first, RandIter nth, RandIter last); template<typename RandIter, typename Compare> void nth_element(RandIter first, RandIter nth, RandIter last, Compare comp);
The nth_element
function template reorders the range [first
, last
) so that the value at nth
is the value that would be there if the entire range were sorted. It also partitions the range so that all elements in the range [first
, nth
) are less than *nth
and the remaining elements are moved to [nth
+ 1, last
).
The standard does not mention stability, so assume that the sorted order is not stable, that is, if there are multiple elements that could be moved to position *nth
and preserve the sorted order, you cannot predict which element will be moved to that position.
Figure 13-10 illustrates how the nth_element
function template works.
Figure 13-10: Example of nth_element
Postcondition: *i < *nth for all i in [first, nth), and !(*j < *nth) for all j in [nth, last).
Complexity is linear for the average case, but is allowed to have worse performance in the worst case.
partition function template, partial_sort function template, sort function template
template<typename RandIter> void partial_sort(RandIter first, RandIter middle, RandIter last); template<typename RandIter, typename Compare> void partial_sort(RandIter first, RandIter middle, RandIter last, Compare comp);
The partial_sort
function template sorts the middle
- first
elements of the range [first
, last
) into the range [first
, middle
). The remaining elements at [middle
, last
) are not in any particular order.
The first form compares values using the <
operator; the second form calls comp(*iter1,
*iter2)
.
See Figure 13-11 (under partial_sort_copy
) for an illustration of the partial sort algorithm.
Postcondition: for all i in [first, middle - 1), *(i + 1) < *i is false, and for all j in [middle, last) and for all i in [first, middle) *j < *i is false.
Complexity is logarithmic, taking about (last - first) × log (middle - first) comparisons.
nth_element function template, partial_sort_copy function template, partition function template, sort function template
template<typename InIter, typename RandIter> RandIter partial_sort_copy(InIter first, InIter last, RandIter result_first, RandIter result_last); template<typename InIter, typename RandIter, typename Compare> RandIter partial_sort_copy(InIter first, InIter last, RandIter result_first, RandIter result_last, Compare comp);
The partial_sort_copy
function template copies and sorts elements from the range [first
, last
) into the range [result_first
, result_last
). The number of items copied (N) is the smaller of last
- first
and result_last
- result_first
. If the result range is smaller than the source range, the sorted elements are taken from the entire source range [first
, last
) and copied into the first N positions of the result range, starting at result_first
. If the source range is larger, it is copied and sorted into the first N positions of the result range, leaving the elements in [result_first
+ N, result_last
) untouched.
The return value is result_first
+ N.
The first form compares values using the <
operator; the second form calls comp(*iter1,
*iter2)
.
Let n = min(last - first, result_last - result_first).
Postcondition: for all i in [result_first, result_first + n), *(i + 1) < *i is false, and *j is unchanged for all j in [result_first + n, result_last).
Complexity is logarithmic, taking about (last - first) × log n comparisons.
nth_element function template, partial_sort_copy function template, partition function template, sort function template
template<typename BidiIter, typename Predicate> BidiIter partition(BidiIter first, BidiIter last, Predicate pred);
The partition
function template swaps elements in the range [first
, last
) so that all elements that satisfy pred
come before those that do not. The relative order of elements is not preserved.
The return value is the an iterator that points to the first element for which pred
is false, or last if there is no such element.
Figure 13-12 illustrates the partition
function template for a predicate that tests whether a number is even:
function iseven(int n) { return n % 2 == 0; }
Figure 13-12: Example of partition
Postcondition: let r be an iterator in the range [first, last] such that pred(*i) is true for all i in [first, r) and pred(*j)is false for all j in [r, last). The return value is r.
Complexity is linear: pred
is called exactly last - first times, and at most (last - first) / 2 swaps are performed.
nth_element function template, partial_sort function template, sort function template, stable_partition function template
template<typename RandIter> void pop_heap(RandIter first, RandIter last); template<typename RandIter, typename Compare> void pop_heap(RandIter first, RandIter last, Compare comp);
The pop_heap
function template removes the first (largest) element from the heap in [first
, last
) and ensures that the elements remaining in [first
, last
- 1) form a heap.
The first form compares values using the <
operator; the second form calls comp(*iter1,
*iter2)
.
Precondition: [first, last) is a heap.
Postcondition: [first, last - 1) is a heap.
Complexity is logarithmic: at most 2 × log(last - first) comparisons are performed.
make_heap function template, priority_queue template class, push_heap function template, sort_heap function template
template<typename BidiIter> bool prev_permutation(BidiIter first, BidiIter last); template<typename BidiIter, typename Compare> bool prev_permutation(BidiIter first, BidiIter last, Compare comp);
The prev_permutation
function template rearranges the contents of the range [first
, last
) to the previous permutation, assuming a set of lexicographically ordered permutations. The return value is true for generating the previous permutation, or false if there are no more permutations, in which case the last permutation is generated (that is, with all elements in lexicographically descending order).
Figure 13-9 (under next_permutation
) depicts all the permutations, in order, for a sequence. The prev_permutation
function swaps elements to form the previous permutation. For example, if the input is permutation 3, the result is permutation 2. If the input is permutation 1, the result is 6, and prev_permutation
returns false.
Complexity is linear: at most (last - first) / 2 swaps.
lexicographical_compare function template, next_permutation function template, swap function template
template<typename RandIter> void push_heap(RandIter first, RandIter last); template<typename RandIter, typename Compare> void push_heap(RandIter first, RandIter last, Compare comp);
The push_heap
function template adds the item at last
- 1 to the heap in [first
, last
- 1), forming a new heap in the range [first
, last
).
The first form compares values using the <
operator; the second form calls comp(*iter1,
*iter2)
.
Precondition: [first, last - 1) is a heap.
Postcondition: [first, last) is a heap.
Complexity is logarithmic: at most log(last - first) comparisons are performed.
make_heap function template, priority_queue template class, pop_heap function template, sort_heap function template
template<typename RandIter> void random_shuffle(RandIter first, RandIter last); template<typename RandIter, typename RandomNumberGenerator> void random_shuffle(RandIter first, RandIter last, RandomNumberGenerator& rand);
The random_shuffle
function template changes the order of elements in the range [first
, last
) to a random order. The first form uses a random number generator to produce a uniform distribution. The second form calls rand
(n) to generate random numbers, where n is a positive value of type iterator_traits<RandIter>::difference_type
. The return value from rand
must be convertible to the same difference_type
and be in the range [0, n).
Complexity is linear: exactly (last - first) + 1 swaps are performed.
swap function template
template<typename FwdIter, typename T> FwdIter remove(FwdIter first, FwdIter last, const T& value);
The remove
function template "removes" items that are equal to value
from the range [first
, last
). The return value is one past the new end of the range. The relative order of items that are not removed is stable.
Nothing is actually erased from the underlying container; instead, items to the right are assigned to new positions so they overwrite the elements that are equal to value
. See Figure 13-13 (under remove_copy
) for an example of the removal process.
Assigns *(first + n++) = *(first + m) where n starts at 0, for all values of m in [0, last - first) where *(first + m) == value is false. Return value is first + n.
Complexity is linear: Exactly last - first comparisons are performed.
remove_copy function template, remove_copy_if function template, remove_if function template, replace function template
template<typename InIter, typename OutIter, typename T> OutIter remove_copy(InIter first, InIter last, OutIter result, const T& value);
The remove_copy
function template copies items from the range [first
, last
) to the range that starts at result. Only items that are not equal to value
are copied, that is, where operator==
returns false.
The return value is one past the new end of the range. The relative order of items that are not removed is stable.
The source and result ranges must not overlap. Figure 13-13 illustrates the removal process.
Figure 13-13: Example of remove_copy(first, last, 18)
Assigns *(result + n++) = *(first + m) where n starts at 0, for all values of m in [0, last - first) where *(first + m) == value is false. Return value is result + n.
Complexity is linear: Exactly last - first comparisons are performed.
remove function template, remove_copy_if function template, replace_copy function template
template<typename InIter, typename OutIter, typename Predicate> OutIter remove_copy_if(InIter first, InIter last, OutIter result, Predicate pred);
The remove_copy_if
function template copies items from the range [first
, last
) to the range that starts at result. Only items for which pred
returns false are copied.
The return value is one past the new end of the range. The relative order of items that are not removed is stable.
The source and result ranges must not overlap. See Figure 13-13 (under remove_copy
) for an example of the removal process.
Assigns *(result + n++) = *(first + m) where n starts at 0, for all values of m in [0, last - first) where pred
(*(first + m)) is false. Return value is result + n.
Complexity is linear: Exactly last - first comparisons are performed.
remove function template, remove_copy function template, replace_copy_if function template
template<typename FwdIter, typename Predicate> FwdIter remove_if(FwdIter first, FwdIter last, Predicate pred);
The remove_if
function template "removes" items for which pred
returns false from the range [first
, last
). The return value is one past the new end of the range. The relative order of items that are not removed is stable.
Nothing is actually erased from the underlying container; instead, items to the right are assigned to new positions so they overwrite the elements for which pred
returns false. See Figure 13-13 (under remove_copy
) for an example of the removal process.
Assigns *(first + n++) = *(first + m) where n starts at 0, for all values of m in [0, last - first) where pred
(*(first + m)) is false. Return value is first + n.
Complexity is linear: Exactly last - first comparisons are performed.
remove function template, remove_copy_if function template, replace_if function template
template<typename FwdIter, typename T> void replace(FwdIter first, FwdIter last, const T& old_value, const T& new_value);
The replace
function template replaces all values in [first
, last
) that are equal to old_value
with new_value
. See Figure 13-14 (under replace_copy
) for an example of the replacement process.
For all i in [first, last) if (*i == old_value) then *i = new_value.
Complexity is linear: example last - first comparisons are performed.
remove function template, replace_copy function template, replace_copy_if function template, replace_if function template, transform function template
template<typename InIter, typename OutIter, typename T> OutIter replace_copy(InIter first, InIter last, OutIter result, const T& old_value, const T& new_value);
The replace_copy
function template copies values from [first
, last
) to the range that starts at result
. Elements that are equal to old_value
are replaced with new_value
; other elements are copied without modification.
The return value is an iterator that points to one past the end of the result range. The source and result ranges must not overlap. Figure 13-14 illustrates the replacement process.
Figure 13-14: Example of replace_copy(first, last, 42, 10)
For all n in [0, last - first), *(result + n) = *(first + n) == old_value ? new_value : *(first + n).
Complexity is linear: example last - first comparisons are performed.
remove_copy function template, replace function template, replace_copy_if function template, transform function template
template<typename Iter, typename OutIter, typename Predicate, typename T> OutIter replace_copy_if(Iter first, Iter last, OutIter result, Predicate pred, const T& new_value);
The replace_copy_if
function template copies values from [first
, last
) to the range that starts at result
. Elements for which pred
returns true are replaced with new_value
; other elements are copied without modification.
The return value is an iterator that points to one past the end of the result range. The source and result ranges must not overlap. See Figure 13-14 (under replace_copy
) for an example of the replacement process.
For all n in [0, last - first), *(result + n) = *(first + n) == pred
(*(first + n)) ? new_value : *(first + n).
Complexity is linear: example last - first comparisons are performed.
remove_copy_if function template, replace function template, replace_copy function template, replace_if function template, transform function template
template<typename FwdIter, typename Predicate, typename T> void replace_if(FwdIter first, FwdIter last, Predicate pred, const T& new_value);
The replace_if
function template replaces all values in [first
, last
) for which pred
is true with new_value
. See Figure 13-14 (under replace_copy
) for an example of the replacement process.
For all i in [first, last) if pred
(*i) then *i = new_value.
Complexity is linear: example last - first comparisons are performed.
remove_if function template, replace function template, replace_copy function template, transform function template
template<typename BidiIter> void reverse(BidiIter first, BidiIter last);
The reverse
function template reverses the order of the items in the range [first
, last
). See Figure 13-15 (under reverse_copy
) for an example.
For all n in [0, (last - first) / 2], swaps *(first + n) with *(last - n - 1).
Complexity is linear: exactly (last - first) / 2 swaps are performed.
reverse_copy function template, rotate function template, swap function template
template<typename BidiIter, typename OutIter> OutIter reverse_copy(BidiIter first, BidiIter last, OutIter result);
The reverse_copy
function template copies items in reverse order from the range [first
, last
) to the range that starts at result
. The return value is an iterator that points to one past the end of the result range.
The source and result ranges must not overlap. Figure 13-15 shows an example of reversing a range.
Figure 13-15: Example of reverse_copy
For all n in [0, last - first), assigns *(result + n) = *(last - n - 1).
Complexity is linear: exactly last - first assignments are performed.
reverse function template, rotate_copy function template
template<typename FwdIter> void rotate(FwdIter first, FwdIter middle, FwdIter last);
The rotate
function template rotates elements in the range [first
, last
) to the left so that the items in the range [middle
, last
) are moved to the start of the new sequence. Elements in the range [first
, middle
) are rotated to the end. See Figure 13-16 (under rotate_copy
) for an example.
For all n in [0, last - first), moves *(first + n) into position first + (n + (last - middle)) % (last - first).
Complexity is linear: at most last - first swaps are performed.
reverse function template, rotate_copy function template
template<typename FwdIter, typename OutIter> OutIter rotate_copy(FwdIter first, FwdIter middle, FwdIter last, OutIter result);
The rotate_copy
function template copies elements from the range [middle
, last
) to the range that starts at result, followed by the elements from [first
, middle
), thereby effecting a rotation to the left. The return value is one past the end of the result range.
The source and result ranges must not overlap. Figure 13-16 shows an example of rotation.
Figure 13-16: Example of rotate_copy
For all n in [0, last - first), assigns *(result + (n + (last - middle)) % (last - first)) = *(first + n). Returns result + (last - first).
Complexity is linear: exactly last - first assignments are performed.
reverse_copy function template, rotate function template
template<typename FwdIter1, typename FwdIter2> FwdIter1 search(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2); template<typename FwdIter1, typename FwdIter2, typename BinaryPredicate> FwdIter1 search(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2, BinaryPredicate pred);
The search
function template finds the first (leftmost) subsequence [first2
, last2
) within the range [first1
, last1
), as illustrated in Figure 13-5 (under find_end
). It returns last1
if the subsequence is not found.
The first form compares items with the ==
operator; the second form calls pred(*iter1,
*iter2)
.
Let length1 = last1 - first1 and length2 = last2 - first2.
Returns first1 + n where n is the smallest value in the range [0, length1 - length2) such that *(i + n + m) == (first2 + m) for all m in the range [0, length2). Returns last1 if no such n can be found.
Complexity is quadratic: at most length1 × length2 comparisons are performed.
find function template, find_end function template, search_n function template
template<typename FwdIter, typename Size, typename T> FwdIter search_n(FwdIter first, FwdIter last, Size count, const T& value); template<typename FwdIter, typename Size, typename T, typename BinaryPredicate> FwdIter search_n(FwdIter first, FwdIter last, Size count, const T& value, BinaryPredicate pred);
The search_n
function template finds the first (leftmost) subsequence of count
adjacent occurrences of value
in the range [first
, last
). It returns an iterator that points to the start of the subsequence, or last
if the subsequence is not found.
The first form compares items with the ==
operator; the second form calls pred(*iter,
value)
.
Returns first + n where n is the smallest value in the range [0, last - first) such that *(i + n + m) == value for all m in the range [0, count). Returns last if no such n can be found.
Complexity is quadratic: at most length1 × length2 comparisons are performed.
find function template, search function template
template<typename InIter1, typename InIter2, typename OutIter> OutIter set_difference(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result); template<typename InIter1, typename InIter2, typename OutIter, typename Compare> OutIter set_difference(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result, Compare comp);
The set_difference
function template copies elements from the sorted range [first1
, last1
) to the range starting at result
. Only those elements that are not also present in the sorted range [first2
, last2
) are copied. An iterator that points to one past the end of the result range is returned.
The result range must not overlap either source range.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Figure 13-17 shows an example of a set difference using multisets.
Figure 13-17: Example of set_difference
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Postcondition: !(*(i - 1) < *i) for all i in [result, return - 1).
Assigns *(result + n++) = *(first1 + m) for all m in [first1, last1) where *(first1 + m) is not in [first2, last2). Returns result + n.
Complexity is linear: at most 2 × ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed.
includes function template, set_intersection function template, set_symmetric_difference function template, set_union function template
template<typename InIter1, typename InIter2, typename OutIter> OutIter set_intersection(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result); template<typename InIter1, typename InIter2, typename OutIter, typename Compare> OutIter set_intersection(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result, Compare comp);
The set_intersection
function template copies elements from the sorted range [first1
, last1
) to the range starting at result
. Only those elements that are also present in the sorted range [first2
, last2
) are copied. An iterator that points to one past the end of the result range is returned.
The result range must not overlap either source range.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Figure 13-18 shows an example of intersection using multisets.
Figure 13-18: Example of set_intersection
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Postcondition: !(*(i - 1) < *i) for all i in [result, return - 1).
Assigns *(result + n++) = *(first1 + m) for all m in [first1, last1) where *(first1 + m) is in [first2, last2). Returns result + n.
Complexity is linear: at most 2 × ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed.
includes function template, set_difference function template, set_symmetric_difference function template, set_union function template
template<typename InIter1, typename InIter2, typename OutIter> OutIter set_symmetric_difference( InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result); template<typename InIter1, typename InIter2, typename OutIter, typename Compare> OutIter set_symmetric_difference( InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result, Compare comp);
The set_symmetric_difference
function template merges elements from the sorted ranges [first1
, last1
) and [first2
, last2
), copying the sorted, merged results to the range starting at result
. Only those elements that are not also present in the sorted range [first2
, last2
) are copied from [first1
, last1
), and only those not present in the range [first1
, last1
) are copied from [first2
, last2
). An iterator that points to one past the end of the result range is returned.
The result range must not overlap either source range.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Figure 13-19 shows an example of a set symmetric difference using multisets.
Figure 13-19: Example of set_difference
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Postcondition: !(*(i - 1) < *i) for all i in [result, return - 1).
Complexity is linear: at most 2 × ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed.
includes function template, set_difference function template, set_intersection function template, set_union function template
template<typename InIter1, typename InIter2, typename OutIter> OutIter set_union(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result); template<typename InIter1, typename InIter2, typename OutIter, typename Compare> OutIter set_union(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, OutIter result, Compare comp);
The set_union
function template merges elements from the sorted ranges [first1
, last1
) and [first2
, last2
), copying the sorted, merged results to the range starting at result
. If an element is present in both ranges, only one element is copied to the result range. If the input ranges are multisets, each occurrence of an element in an input range results in a copy in the result range. An iterator that points to one past the end of the result range is returned.
The result range must not overlap either source range.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Figure 13-20 shows an example of a set union using multisets.
Figure 13-20: Example of set_union
Precondition: !(*(i - 1) < *i) for all i in [first1, last1 - 1) and !(*(j - 1) < *j) for all j in [first2, last2 - 1).
Postcondition: !(*(i - 1) < *i) for all i in [result, return - 1).
Complexity is linear: at most 2 × ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed.
includes function template, merge function template, set_difference function template, set_intersection function template, set_symmetric_difference function template
template<typename RandIter> void sort(RandIter first, RandIter last); template<typename RandIter, typename Compare> void sort(RandIter first, RandIter last, Compare comp);
The sort
function template sorts the range [first
, last
) in place. The sort is not stable, so equivalent elements do not preserve their original order.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Postcondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Complexity is n log n comparisons in the average case, where n = last - first. Worst case performance might be worse.
merge function template, nth_element function template, partial_sort function template, partition function template, sort_heap function template, stable_sort function template
template<typename RandIter> void sort_heap(RandIter first, RandIter last); template<typename RandIter, typename Compare> void sort_heap(RandIter first, RandIter last, Compare comp);
The sort_heap function template sorts a heap in the range [first, last). The sort is not stable, so equivalent elements do not preserve their original order.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Precondition: [first, last) is a heap.
Postcondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Complexity is at most n log n comparisons, where n = last - first.
make_heap function template, priority_queue template class, pop_heap function template, push_heap function template, sort function template
template<typename BidiIter, typename Predicate> BidiIter stable_partition(BidiIter first, BidiIter last, Predicate pred);
The stable_partition
function template swaps elements in the range [first
, last
) so that all elements that satisfy pred
come before those that do not. The relative order of elements in each partition is preserved.
The return value is the an iterator that points to the first element for which pred
is false, or last
if there is no such element.
Figure 13-12 (under partition
) illustrates the partition functionality.
Postcondition: let r be an iterator in the range [first, last] such that pred(*i) is true for all i in [first, r) and pred(*j)is false for all j in [r, last). The return value is r.
Complexity is linear if there is enough memory. Otherwise, at most n log n swaps are performed, where n = last - first. In all cases, pred
is called exactly n times.
nth_element function template, partial_sort function template, partition function template, stable_sort function template
template<typename RandIter> void stable_sort(RandIter first, RandIter last); template<typename RandIter, typename Compare> void stable_sort(RandIter first, RandIter last, Compare comp);
The stable_sort
function template sorts the range [first
, last
) in place. The sort is stable, so equivalent elements preserve their original order.
The first version compares items using the <
operator. The second version uses comp(X,
Y)
to test whether X
<
Y
.
Postcondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Complexity is at most n log n comparisons, where n = last - first., provided enough memory is available for temporary results. If memory is limited, the complexity is at most n (log n)2 comparisons.
merge function template, nth_element function template, partial_sort function template, sort function template, sort_heap function template, stable_partition function template
template<typename T> void swap(T& a, T& b);
The swap
function template swaps the values of a
and b
.
iter_swap function template, swap_ranges function template
template<typename FwdIter1, typename FwdIter2> FwdIter2 swap_ranges(FwdIter1 first1, FwdIter1 last1, FwdIter2 first2);
The swap_ranges function template swaps all the elements in [first1, last1) with corresponding elements in the range that starts at first2 (and has the same length as the first range). The return value is one past the end of the second range. The two ranges must not overlap.
For all n in [0, last1 - first1), performs swap(*(first1 + n), *(first2 + n));
Complexity is linear: exactly last1 - first1 swaps are performed.
iter_swap function template, swap function template
template<typename InIter, typename OutIter, typename UnaryOperation> OutIter transform(InIter first, InIter last, OutIter result, UnaryOperation unop); template<typename InIter1, typename InIter2, typename OutIter, typename BinaryOperation> OutIter transform(InIter1 first1, InIter1 last1, InIter2 first2, OutIter result, BinaryOperation binop);
The transform
function template assigns a new value to each element in the range that starts at result
. In the first case, the new value is unop(*iter)
, where iter is an iterator over [first
, last
). In the second case, the new value is binop(*iter1
, *iter2)
, where iter1 ranges over [first1
, last1
) and iter2
is over the range that starts at first2
.
The return value is one past the end of the result range. The result range can be the same as any of the input ranges.
First form assigns *(result + n) = unop
(*(first + n)) for all n in [0, last - first).
Second form assigns *(result + n) = binop
(*(first1 + n), *(first2 + n)) for all n in [0, last1 - first1).
Complexity is linear: unop
or binop
is called exactly n times, where n = first - last for a unary operator or last1 - first1 for a binary operator.
copy function template, for_each function template
template<typename FwdIter> FwdIter unique(FwdIter first, FwdIter last); template<typename FwdIter, typename BinaryPredicate> FwdIter unique(FwdIter first, FwdIter last, BinaryPredicate pred);
The unique
function template "removes" repetitions of adjacent, identical elements from the range [first
, last
). The return value is one past the new end of the range. For each sequence of identical elements, only the first is kept.
Nothing is actually erased from the underlying container; instead, items to the right are assigned to new positions so they overwrite the elements that are duplicates. See Figure 13-21 (under unique_copy
) for an example of the removal process.
The first form compares items with the ==
operator; the second form calls pred(a, b)
.
Assigns *(first + n++) = *(first + m) for all m in [0, last - first), where m == 0 or *(first +m) == *(first + m - 1) is false. Returns first + n.
Complexity is linear: exactly max(0, last - first - 1) comparisons are performed.
remove function template, unique_copy function template
template<typename InIter, typename OutIter> OutIter unique_copy(InIter first, InIter last, OutIter result); template<typename InIter, typename OutIter, typename BinaryPredicate> OutIter unique_copy(InIter first, InIter last, OutIter result, BinaryPredicate pred);
The unique_copy
function template copies items from [first
, last
) to the range that start at result
. For each sequence of identical elements, only the first is kept. The return value is one past the end of the result range.
The first form compares items with the ==
operator; the second form calls pred(a, b)
.
See Figure 13-21 for an example calling unique_copy
.
Figure 13-21: Example of unique_copy
Assigns *(result + n++) = *(first + m) for all m in [0, last - first), where m == 0 or *(first +m) == *(first + m - 1) is false. Returns result + n.
Complexity is linear: exactly last - first comparisons are performed.
remove_copy function template, unique function template
template<typename FwdIter, typename T> FwdIter upper_bound(FwdIter first, FwdIter last, const T& value); template<typename FwdIter, typename T, typename Compare> FwdIter upper_bound(FwdIter first, FwdIter last, const T& value, Compare comp);
The upper_bound
function template determines where value
belongs in the sorted range [first
, last
). It returns an iterator that points to the last (rightmost) position where you can insert value
and preserve the sorted nature of the range.
The first form compares values using the <
operator; the second form calls comp(*iter
, value)
.
Figure 13-4 (under equal_range
) shows an example of finding the bounds for the value 36. Note that for values in the range [19, 35], lb
is the upper bound, and for values in the range [37, 41], ub
is the upper bound.
Precondition: !(*(i - 1) < *i) for all i in [first, last - 1).
Returns first + n where n is the highest value in [0, last - first) such that *(first + m) < value is false for all m in [0, n).
Complexity is logarithmic in the number of comparisons, which is at most log(last - first) + 1. Although the iterator can be a forward iterator, the best performance is obtained with a random access iterator. With a forward or bidirectional iterator, a linear number of steps is required (even though the number of comparisons is still logarithmic).
binary_search function template, equal_range function template, lower_bound function template