13.1 <algorithm>The <algorithm> header declares the generic algorithm function templates for operating on iterators and other objects. Refer to Chapter 10 for more information about using and writing generic algorithms and about the iterators they use. See Chapter 8 for a discussion of iterator traits.
This section uses a number of abbreviations and conventions. First, each algorithm is described using plain English. Then, a more mathematical description of the algorithm, which tends to be harder to read, is given in a "Technical Notes" section. The names of the template parameters tell you which category of iterator is expected. The iterator category is the minimal functionality needed, so you can, for example, use a random access iterator where at least a forward iterator is needed. (See Chapter 10 for more information on iterators and iterator categories.) To keep the syntax summaries short and readable, the iterator categories are abbreviated, as shown in Table 13-1.
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 Boolean functional object (an object that has a function call operator that returns a Boolean result). A number of algorithms require sorted ranges or otherwise use a comparison function to test the less-than relationship. The library overloads each algorithm: the first function uses operator<, and the second accepts a function pointer or function object to perform the comparison. The comparison function takes two arguments and returns a Boolean result. In the "Technical Notes" sections, the < relationship signifies operator< or the caller-supplied function, depending on the version of the algorithm you are using. If you overload operator< or provide your own comparison function, make sure it correctly implements a less-than relationship. In particular, a < a must be false for any a. In this section, the following conventions are used:
In each "Technical Notes" section, conventional mathematical notation is used with some aspects of C++ notation, such as *, which dereferences an iterator. Also, a single equal sign (=) means assignment, and a double equal sign (==) means comparison for equality. The following conventions are used for names:
The adjacent_find function template looks for the first set of adjacent items in the range [first, last) that are equal (first version) or in which pred(*iter, (*iter+1)) is true (second version). Items are "adjacent" when their iterators differ by one position. 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. Using adjacent_find to find two adjacent, equivalent itemsTechnical NotesThe adjacent_find function template returns i, in which i = first + n, and n is the smallest value such that *(first + n) == *(first + n + 1) and first + n + 1 < last, or, if there is no such n, i = last. Complexity is linear: the standard is muddled, but any reasonable implementation calls the predicate (operator== or pred) exactly n + 1 times. See Alsofind function template, find_if function template
The binary_search function template uses a binary search to test whether value is in the range [first, last). It returns true upon success and false if the value is not found. The contents of the range must be sorted in ascending order. The first version compares items using the < operator. The second version uses comp(X, Y) to test whether X < Y. Technical NotesPrecondition: !(*(i + 1) < *i) for all i in [first, last - 1). The binary_search function template returns true if there is an i in [first, last) such that !(*i < value) and !(value < *i). It returns false if there is no such i. Complexity is logarithmic. The number of comparisons 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, the iterator is advanced a linear number of times, even though the number of comparisons is logarithmic. See Alsoequal_range function template, find function template, find_if function template, lower_bound function template, upper_bound function template
The copy function template copies items from [first, last) to the output iterator starting at result. You must ensure that the output sequence has enough room for last - first items. The return value is the value of the result iterator after copying all the items, as shown in Figure 13-2. Figure 13-2. Copying a rangeThe result iterator cannot be in the source range [first, last), but other parts of the destination range can overlap with the source. See Example 13-2 (under generate). Technical NotesThe copy function template assigns *(result + n) = *(first + n) for all n in the range [0, last - first). Complexity is linear: exactly last - first assignments are performed. See Alsocopy_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
The copy_backward function template does the same thing as copy, but it works backward, starting at the element before last and copying elements toward first. The result iterator must point to one past the end of the destination and is decremented before copying each element. The return value is an iterator that points to the first element of the destination, as shown in Figure 13-3. Figure 13-3. Copying a range backwardThe result iterator cannot be in the source range [first, last), but other parts of the destination range can overlap with the source. Technical NotesThe copy_backward function template assigns *(result - n) = *(last - n) for all n in the range [1, last - first]. Complexity is linear: exactly last - first assignments are performed. See Alsocopy function template, reverse_copy function template
The count function template returns the number of elements in the range [first, last) that are equal to value. Technical NotesComplexity is linear: exactly last - first comparisons are performed. See Alsocount_if function template, equal_range function template
The count_if function template returns the number of elements in the range [first, last) for which pred(*iter) returns true. Technical NotesComplexity is linear: pred is called exactly last - first times. See Alsocount function template, find_if function template
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). Technical NotesThe equal function template 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. See Alsolexicographical_compare function template, mismatch function template, search function template
The equal_range function template determines where value belongs in the sorted range [first, last). It returns a pair of iterators that specify the start and one past the end of the range of items that are equivalent to value, or both iterators in the pair point to 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 how bounds are found with the value 36. The result of calling equal_range is pair(lb, ub). Note that for values in the range [19, 35], the upper and lower bound are both equal to lb, and for values in the range [37, 41], the upper and lower bound are both equal to ub. Figure 13-4. Finding the limits of where the value 36 belongs in a sorted rangeTechnical NotesPrecondition: !(*(i + 1) < *i) for all i in [first, last - 1). The equal_range function template 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. The number of comparisons is at most 2 x 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, the iterator is advanced a linear number of times, even though the number of comparisons is logarithmic. See Alsobinary_search function template, lower_bound function template, upper_bound function template, pair in <utility>
The fill function template fills the destination range [first, last) by assigning value to each item in the range. Technical NotesThe fill function template assigns *i = value for all i in the range [first, last). Complexity is linear: exactly last - first assignments are performed. See Alsofill_n function template, generate function template
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. Technical NotesThe fill_n function template assigns *(first + n) = value for all n in the range [0, n). Complexity is linear: exactly n assignments are performed. See Alsofill function template, generate_n function template
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 is used to compare items. Technical NotesThe find function template returns i = first + n, in which n is the smallest value such that *(first + n) == value. If there is no such n, i = last. Complexity is linear: at most last - first comparisons are performed. See Alsofind_end function template, find_first function template, find_if function template, search function template
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 an iterator, find_end in Figure 13-5, that points to the start of the matching subsequence or last1 if a match cannot be found. The first form compares items with the == operator. The second form calls pred(*iter1, *iter2). Figure 13-5. Finding a subsequence with find_end and searchTechnical NotesLet length1 = last1 - first1 and length2 = last2 - first2. The find_end function template returns first1 + n, in which n is the highest value in the range [0, length1 - length2) such that *(i + n + m) == (first2 + m) for all i in the range [first1, last1) and m in the range [0, length2). It returns last1 if no such n can be found. Complexity: at most length1 x length2 comparisons are performed. See Alsofind function template, search function template
The find_first_of function template searches the range [first1, last1) for any one of the items in [first2, last2). If it finds a matching item, it returns an iterator that points to the matching item, in the range [first1, last1). It returns last1 if no matching item is found. Figure 13-6 shows an example. Figure 13-6. Finding any one of a list of itemsThe first form compares items with the == operator. The second form calls pred(*iter1, *iter2). Technical NotesLet length1 = last1 - first1 and length2 = last2 - first2. The find_first_of function template 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). It returns last1 if no such n and m can be found. Complexity: at most length1 x length2 comparisons are performed. See Alsofind function template
The find_if function template (similar to find) searches the range [first, last) for the first item for which pred(*iter) is true. It returns an iterator that points to the matching item. If no matching item is found, last is returned. Technical NotesThe find_if function template returns i = first + n, in which n is the smallest value such that pred(*(first + n), value) is true. If there is no such n, i = last. Complexity is linear: pred is called at most last - first times. See Alsofind function template
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. ExampleExample 13-1 shows how the use for_each to test whether a sequence is sorted. The is_sorted object remembers the previous item in the sequence, which it compares with the current item. The overloaded bool operator returns true if the sequence is sorted so far 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" << '\n'; } Technical NotesComplexity is linear: f is called exactly last - first times. See Alsocopy function template, accumulate in <numeric>
The generate function template fills the sequence [first, last) by assigning the result of calling gen( ) repeatedly. ExampleExample 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". 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")); } Technical NotesComplexity is linear: gen is called exactly last - first times. See Alsofill function template, generate_n function template
The generate_n function template calls gen( ) exactly n times, assigning the results to fill the sequence 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. ExampleExample 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)); } Technical NotesComplexity is linear: gen is called exactly n times. See Alsofill_n function template , generate function template
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 compare the elements. The second form calls comp(*iter1, *iter2). Technical NotesPrecondition: !(*(i + 1) < *i) for all i in [first1, last1 - 1) and !(*(j + 1) < *j) for all j in [first2, last2 - 1). The includes function template returns true if there is an i in [first1, last1) such that *(i + n) = *(first2 + n) for all n in [0, (last2 - first2)). It returns last1 if there is no such i. Complexity is linear: at most, 2 x ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed. See Alsoset_difference function template, set_intersection function template, set_symmetric_difference function template, set_union function template
The inplace_merge function template merges two sorted, consecutive ranges in 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 shows how inplace_merge operates. Figure 13-7. Merging two sorted rangesTechnical NotesPrecondition: !(*(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). Complexity is usually linear with n + 1 comparisons, but if enough temporary memory is not available, the complexity might be n log n, in which n is last - first. See Alsomerge function template, sort function template
The iter_swap function template swaps the values pointed to by a and b. You can think of its functionality as: FdwIter1::value_type tmp = *b*; *b = *a; *a = tmp; Technical NotesComplexity is constant. See Alsocopy function template, swap function template, swap_ranges function template
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 use of "lexicographical" emphasizes that the ranges are compared element-wise, like letters in words.) The first form uses the < operator to compare elements. The second form calls comp(*iter1, *iter2). Technical NotesLet length1 = last1 - first1, length2 = last2 - first2, and minlength = min(length1, length2). The lexicographical_compare function template returns true if either of the following conditions is true:
Complexity is linear: at most, minlength comparisons are performed. Example#include <algorithm> #include <iostream> #include <ostream> int main( ) { using namespace std; int a[] = { 1, 10, 3, 42 }; int b[] = { 1, 10, 42, 3 }; int c[] = { 1, 10 }; cout << boolalpha; cout << lexicographical_compare(a, a+4, b, b+4); // true cout << lexicographical_compare(a, a+4, c, c+2); // false cout << lexicographical_compare(a, a+4, a, a+4); // false cout << lexicographical_compare(c, c+2, b, b+4); // true } See Alsoequal function template
The lower_bound function template determines where value belongs in the sorted range [first, last). The return value is an iterator that points to the first (leftmost) occurrence of value in the range, if value is present. Otherwise, the iterator points to the first 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 how to find the bounds for the value 36. The lower_bound function returns lb as the lower bound of 36 in the given range. Note that lb is the lower bound for all values in the range [19, 36], and for values in the range [37, 41], the lower bound is equal to ub. Technical NotesPrecondition: !(*(i + 1) < *i) for all i in [first, last - 1). The lower_bound function template returns first + n, in which n is the highest value in [0, last - first) such that *(first + m) < value for all m in [0, n). Complexity is logarithmic. The number of comparisons 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, the iterator is advanced a linear number of times, even though the number of comparisons is logarithmic. See Alsobinary_search function template, equal_range function template, upper_bound function template
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).
Technical NotesPostcondition: [first, last) is a heap. Complexity is linear: at most, 3 x (last - first) comparisons are performed. See Alsopop_heap function template, push_heap function template, sort_heap function template, <queue>
The max function template returns the larger of a and b. If neither is larger, it returns a. The first form compares values using the < operator. The second form calls comp(a, b). See Alsomax_element function template, min function template
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). Technical NotesThe max_element function template returns first + n, in which 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. See Alsomax function template, min_element function template
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 that 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). Technical NotesLet length1 = last1 - first1 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 - 1). Complexity is linear: at most, length1 + length2 - 1 comparisons are performed. See Alsoinplace_merge function template, sort function template
The min function template returns the smaller of a and b. If neither is smaller, it returns a. The first form compares values using the < operator. The second form calls comp(a, b). See Alsomax function template, min_element function template
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). Technical NotesThe min_element function template returns first + n, in which 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. See Alsomax_element function template, min function template
The mismatch function template compares two sequences pairwise and returns a pair of iterators that identifies the first elements at which 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 an element of the first sequence, and second member of the pair points to an element of the second sequence. The two iterators have the same offset within their 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 (let's 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. Checking two sequences for a mismatchTechnical NotesThe mismatch function template returns the pair (first1 + n, first2 + n), in which 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. See Alsoequal function template, search function template, pair in <utility>
The next_permutation function template rearranges the contents of the range [first, last) for the next permutation, assuming that there is a set of lexicographically ordered permutations. The return value is true if the next permutation is generated, or false if the range is at the last permutation, in which case the function cycles, and the first permutation is generated (that is, with all elements in ascending order). Figure 13-9 shows 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 permutation 1, and next_permutation returns false. Figure 13-9. Permutations of a sequenceExampleExample 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 <istream> #include <iterator> #include <ostream> #include <vector> void print(const std::vector<int>& v) { std::copy(v.begin( ), v.end( ), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } int main( ) { std::cout << "Enter a few integers, followed by EOF:"; std::istream_iterator<int> start(std::cin); std::istream_iterator<int> end; std::vector<int> v(start, end); // 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); } Technical NotesComplexity is linear: at most, there are (last - first) / 2 swaps. See Alsolexicographical_compare function template, prev_permutation function template, swap function template
The nth_element function template reorders the range [first, last) so that *nth is assigned 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 or equal to the elements in the range [nth, last). The 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. Reordering a range with nth_elementTechnical NotesPrecondition: nth is in the range [first, last). Postcondition: *i < *nth for all i in [first, nth), !(*j < *nth) for all j in [nth, last), and !(*k < *nth) for all k in [nth + 1, last). Complexity is linear for the average case but is allowed to perform worse in the worst case. See Alsopartition function template, partial_sort function template, sort function template
The partial_sort function template sorts the initial 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 for an illustration of the partial-sort algorithm. Figure 13-11. The partial-sort algorithmTechnical NotesPostcondition: 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) x log(middle - first) comparisons. See Alsonth_element function template, partial_sort_copy function template, partition function template, sort function template
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 source range is smaller than the result 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) unmodified. The return value is result_first + N. The first form compares values using the < operator. The second form calls comp(*iter1, *iter2). Technical NotesLet n = min(last - first, result_last - result_first). Postcondition: for all i in [result_first, result_first + n - 1), *(i + 1) < *i is false. Complexity is logarithmic, taking about (last - first) x log n comparisons. See Alsonth_element function template, partial_sort_copy function template, partition function template, sort function template
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 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. Partitioning a range into even and odd numbersTechnical NotesPostcondition: 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 partition function template returns r. Complexity is linear: pred is called exactly last - first times, and at most (last - first) / 2 swaps are performed. See Alsonth_element function template, partial_sort function template, sort function template, stable_partition function template
The pop_heap function template copies the first (largest) element from the heap in [first, last) to the end of the range, that is, *(last - 1). It then 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). Technical NotesPrecondition: [first, last) is a heap (see make_heap for the definition of a heap). Postcondition: [first, last - 1) is a heap, and !(*(last - 1) < *i) for all i in [first, last - 1). Complexity is logarithmic: at most 2 x log(last - first) comparisons are performed. See Alsomake_heap function template, push_heap function template, sort_heap function template, <queue>
The prev_permutation function template rearranges the contents of the range [first, last) to the previous permutation, assuming that there is a set of lexicographically ordered permutations. The return value is true if the previous permutation is generated, or false if the range is at the first permutation, in which case the function cycles and generates the last permutation (that is, with all elements in descending order). Figure 13-9 (under next_permutation) shows 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 permutation 6, and prev_permutation returns false. Technical NotesComplexity is linear: at most (last - first) / 2 swaps are performed. See Alsolexicographical_compare function template, next_permutation function template, swap function template
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). Technical NotesPrecondition: [first, last - 1) is a heap (see make_heap for the definition of a heap). Postcondition: [first, last) is a heap. Complexity is logarithmic: at most log(last - first) comparisons are performed. See Alsomake_heap function template, pop_heap function template, sort_heap function template, <queue>
The random_shuffle function template changes the order of elements in the range [first, last) to a random order. The first form uses an implementation-defined random number generator to produce a uniform distribution. The second form calls rand(n) to generate random numbers, in which 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). Technical NotesComplexity is linear: exactly (last - first) + 1 swaps are performed. See Alsoswap function template, rand in <cstdlib>
The remove function template "removes" items that are equal to value from the range [first, last). Nothing is actually erased from the range; instead, items to the right are copied to new positions so they overwrite the elements that are equal to value. The return value is one past the new end of the range. The relative order of items that are not removed is stable.
See Figure 13-13 (under remove_copy) for an example of the removal process. Technical NotesThe remove function template assigns *(first + n++) = *(first + m), in which n starts at 0, for all values of m in [0, last - first) in which *(first + m) == value is false. The return value is first + n. Complexity is linear: exactly last - first comparisons are performed. See Alsoremove_copy function template, remove_copy_if function template, remove_if function template, replace function template
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, cases in which operator== returns false. The return value is one past the end of the result 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. Removing 18s from a range by calling remove_copy(first, last, 18)Technical NotesThe remove_copy function template assigns *(result + n++) = *(first + m), in which n starts at 0, for all values of m in [0, last - first), in which *(first + m) == value is false. The return value is result + n. Complexity is linear: exactly last - first comparisons are performed. See Alsoremove function template, remove_copy_if function template, replace_copy function template
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 end of the result 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. Technical NotesThe remove_copy_if function template assigns *(result + n++) = *(first + m), in which n starts at 0, for all values of m in [0, last - first), in which pred(*(first + m)) is false. The return value is result + n. Complexity is linear: exactly last - first comparisons are performed. See Alsoremove function template, remove_copy function template, replace_copy_if function template
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. Technical NotesThe remove_if function template assigns *(first + n++) = *(first + m), in which n starts at 0, for all values of m in [0, last - first), in which pred(*(first + m)) is false. The return value is first + n. Complexity is linear: exactly last - first comparisons are performed. See Alsoremove function template, remove_copy_if function template, replace_if function template
The replace function template replaces all occurrences of old_value in [first, last) with new_value. See Figure 13-14 (under replace_copy) for an example of the replacement process. Technical NotesThe replace function template assigns *i = (*i == old_value) ? new_value : *i for all i in [first, last). Complexity is linear: exactly last - first comparisons are performed. See Alsoremove function template, replace_copy function template, replace_copy_if function template, replace_if function template, transform function template
The replace_copy function template copies values from [first, last) to the range that starts at result. Values that are equal to old_value are replaced with new_value; other values 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. Replacing all occurrences of 42 with 10Technical NotesThe replace_copy function template assigns *(result + n) = *(first + n) == old_value ? new_value : *(first + n) for all n in [0, last - first). Complexity is linear: exactly last - first comparisons are performed. See Alsoremove_copy function template, replace function template, replace_copy_if function template, transform function template
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. Technical NotesThe replace_copy_if function template assigns *(result + n) = *(first + n) == pred(*(first + n)) ? new_value : *(first + n) for all n in [0, last - first). Complexity is linear: exactly last - first comparisons are performed. See Alsoremove_copy_if function template, replace function template, replace_copy function template, replace_if function template, transform function template
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. Technical NotesThe replace_if function template assigns *i = pred(*i) ? new_value : *i for all i in [first, last). Complexity is linear: exactly last - first comparisons are performed. See Alsoremove_if function template, replace function template, replace_copy function template, transform function template
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. Technical NotesThe reverse function template swaps *(first + n) with *(last - n - 1) for all n in [0, (last - first) / 2]. Complexity is linear: exactly (last - first) / 2 swaps are performed. See Alsoreverse_copy function template, rotate function template, swap function template
The reverse_copy function template copies items in reverse order from the range [first, last) to the range that starts at result. In other words, *(last - 1) is first copied to *result, then *(last - 2) is copied to *(result + 1), and so on. 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. Reversing a rangeTechnical NotesThe reverse_copy function template assigns *(result + n) = *(last - n - 1) for all n in [0, last - first). Complexity is linear: exactly last - first assignments are performed. See Alsocopy_backward function template, reverse function template, rotate_copy function template
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 for an example. Figure 13-16. Rotating a range by two positionsTechnical NotesFor all n in [0, last - first), the rotate function template moves *(first + n) into position first + (n + (last - middle)) % (last - first). Complexity is linear: at most last - first swaps are performed. See Alsoreverse function template, rotate_copy function template
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. Technical NotesThe rotate_copy function template assigns *(result + (n + (last - middle)) % (last - first)) = *(first + n) for all n in [0, last - first). It returns result + (last - first). Complexity is linear: exactly last - first assignments are performed. See Alsoreverse_copy function template, rotate function template
The search function template finds the first (leftmost) subsequence [first2, last2) within the range [first1, last1). It returns an iterator that points to the start of the subsequence or 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 (under find_end) illustrates the search function template. Technical NotesLet length1 = last1 - first1 and length2 = last2 - first2. The search function template returns first1 + n, in which 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). It returns last1 if no such n can be found. Complexity: at most length1 x length2 comparisons are performed. See Alsofind function template, find_end function template, search_n function template
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). Technical NotesThe search_n function template returns first + n, in which 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). It returns last if no such n can be found. Complexity: at most n x (last - first) comparisons are performed. See Alsofind function template, search function template
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. Computing the difference between setsTechnical NotesPrecondition: !(*(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). The set_difference function template assigns *(result + n++) = *(first1 + m) for all m in [first1, last1), in which *(first1 + m) is not in [first2, last2). It returns result + n. Complexity is linear: at most 2 x ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed. See Alsoincludes function template, set_intersection function template, set_symmetric_difference function template, set_union function template
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. Intersecting two setsTechnical NotesPrecondition: !(*(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). The set_intersection function template assigns *(result + n++) = *(first1 + m) for all m in [first1, last1), in which *(first1 + m) is in [first2, last2). It returns result + n. Complexity is linear: at most 2 x ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed. See Alsoincludes function template, set_difference function template, set_symmetric_difference function template, set_union function template
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. Computing the symmetric difference between two setsTechnical NotesPrecondition: !(*(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 x ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed. See Alsoincludes function template, set_difference function template, set_intersection function template, set_union function template
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 contain duplicates, 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. Computing the union of two setsTechnical NotesPrecondition: !(*(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 x ((last1 - first1) + (last2 - first2)) - 1 comparisons are performed. See Alsoincludes function template, merge function template, set_difference function template, set_intersection function template, set_symmetric_difference function template
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. Technical NotesPostcondition: !(*(i + 1) < *i) for all i in [first, last - 1). Complexity is n log n comparisons in the average case, in which n = last - first. Worst case performance might be worse. Use stable_sort if the worst-case performance is more important than the average performance. See Alsomerge function template, nth_element function template, partial_sort function template, partition function template, sort_heap function template, stable_sort function template
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. Technical NotesPrecondition: [first, last) is a heap (see make_heap for the definition of a heap). Postcondition: !(*(i + 1) < *i) for all i in [first, last - 1). Complexity is at most n log n comparisons, in which n = last - first. See Alsomake_heap function template, pop_heap function template, push_heap function template, sort function template, <queue>
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 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. Technical NotesPostcondition: 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 stable_partition function template returns r. Complexity is linear if there is enough memory. Otherwise, at most n log n swaps are performed, in which n = last - first. In all cases, pred is called exactly n times. See Alsonth_element function template, partial_sort function template, partition function template, stable_sort function template
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. Technical NotesPostcondition: !(*(i + 1) < *i) for all i in [first, last - 1). Complexity is at most n log n comparisons, in which n = last - first, provided that enough memory is available for temporary results. If memory is limited, the complexity is at most n (log n)2 comparisons. See Alsomerge function template, nth_element function template, partial_sort function template, sort function template, sort_heap function template, stable_partition function template
The swap function template swaps the values of a and b. The standard containers all specialize the swap template to call their swap member functions, which usually run in constant time, regardless of the number of elements in the containers. See Alsoiter_swap function template, swap_ranges function template
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. Technical NotesThe swap_ranges function template performs the equivalent of swap(*(first1 + n), *(first2 + n)) for all n in [0, last1 - first1). Complexity is linear: exactly last1 - first1 swaps are performed. See Alsoiter_swap function template, swap function template
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), in which iter is an iterator over [first, last). In the second case, the new value is binop(*iter1, *iter2), in which iter1 ranges over [first1, last1) and iter2 iterates over the range that starts at first2. The second input range must be at least as long as the first. 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. Technical NotesThe first form of transform assigns *(result + n) = unop(*(first + n)) for all n in [0, last - first). The 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, in which n = last - first for a unary operator or last1 - first1 for a binary operator. See Alsocopy function template, for_each function template
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. The input range does not have to be sorted, but if it is, all duplicates are "removed," leaving only unique values (hence the function's name). Nothing is actually erased from the underlying container; instead, items to the right are copied to new positions at lower indices (to the left) 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). Technical NotesThe unique function template assigns *(first + n++) = *(first + m) for all m in [0, last - first), in which m == 0 or *(first +m) == *(first + m - 1) is false. It returns first + n. Complexity is linear: exactly max(0, last - first - 1) comparisons are performed. See Alsoremove function template, unique_copy function template
The unique_copy function template copies items from [first, last) to the range that starts at result, removing duplicates. 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 that calls unique_copy. Figure 13-21. Copying unique elementsTechnical NotesThe unique_copy function template assigns *(result + n++) = *(first + m) for all m in [0, last - first), in which m == 0 or *(first +m) == *(first + m - 1) is false. It returns result + n. Complexity is linear: exactly last - first comparisons are performed. See Alsoremove_copy function template, unique function template
The upper_bound function template determines where value belongs in the sorted range [first, last). The return value is an iterator that points to one past the last (rightmost) occurrence of value in the range, if value is present. Otherwise, the iterator points to the last 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. The upper_bound function returns ub as the upper bound of 36 in the given range. Note that it returns ub as the upper bound for all values in the range [36, 41]. For values in the range [19, 35], the upper bound is equal to lb. Technical NotesPrecondition: !(*(i + 1) < *i) for all i in [first, last - 1). The upper_bound function template returns first + n, in which 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. The number of comparisons 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, the iterator is advanced a linear number of times, even though the number of comparisons is logarithmic. See Alsobinary_search function template, equal_range function template, lower_bound function template |