Professional Documents
Culture Documents
18.8.4.2 Matching Full Texts: Std::regex - Match
18.8.4.2 Matching Full Texts: Std::regex - Match
18.8.4.2 Matching Full Texts: Std::regex - Match
Chapter 19
The STL Generic Algorithms
19.1 The Generic Algorithms
Before using the generic algorithms presented in this chapter, except for those in the Operators
category (defined below), the <algorithm> header file must be included. Before using a generic
algorithm in the Operators category the <numeric> header file must be included.
In the previous chapter the Standard Template Library (STL) was introduced. An important element
of the STL, the generic algorithms, was not covered in that chapter as they form a fairly
extensive part of the STL. Over time the STL has grown considerably, mainly as a result of a growing
importance and appreciation of templates. Covering generic algorithm in the STL chapter itself
would turn that chapter into an unwieldy one and so the generic algorithms were moved to a chapter
of their own.
Generic algorithms perform an amazing task. Due to the strength of templates, algorithms could
be developed that can be applied to a wide range of different data types while maintaining type
safety. The prototypical example of this is the sort generic algorithm. To contrast: while C requires
programmers to write callback functions in which type-unsafe void const _ parameters have to
be used, internally forcing the programmer to resort to casts, STL’s sort frequently allows the
programmer merely to state something akin to
sort(first-element, last-element)
Generic algoritms should be used wherever possible. Avoid the urge to design your own code for commonly
encountered algorithms. Make it a habit to first thoroughly search the generic algorithms for
an available candidate. The generic algorithms should become your weapon of choice when writing
code: acquire full familiarity with them and make their use your ‘second nature’.
This chapter’s sections cover the STL’s generic algorithms in alphabetical order. For each algorithm
the following information is provided:
• The required header file;
• The function prototype;
• A short description;
• A short example.
535
536 CHAPTER 19. THE STL GENERIC ALGORITHMS
In the prototypes of the algorithms Type is used to specify a generic data type. Furthermore, the particular
type of iterator (see section 18.2) that is required is mentioned as well as other generic types
that might be required (e.g., performing BinaryOperations, like plus<Type>). Although iterators
are commonly provided by abstract containers and comparable pre-defined data structrues, at
some point you may want to design your own iterators. Section 22.14 offers guidelines for constructing
your own iterator classes and provides an overview of of operators that must be implemented for
the various types of iterators.
Almost every generic algorithm expects an iterator range [first, last), defining the series of
elements on which the algorithm operates. The iterators point to objects or values. When an iterator
points to a Type value or object, function objects used by the algorithms usually receive Type
const & objects or values. Usually function objects cannot modify the objects they receive as their
arguments. This does not hold true for modifying generic algorithms, which are of course able to
modify the objects they operate upon.
Generic algorithms may be categorized. The C++ Annotations distinguishes the following categories
of generic algorithms:
• Comparators: comparing (ranges of) elements:
equal; includes; lexicographical_compare; max; min; mismatch;
• Copiers: performing copy operations:
copy; copy_backward; partial_sort_copy; remove_copy; remove_copy_if; replace_copy;
replace_copy_if; reverse_copy; rotate_copy; unique_copy;
• Counters: performing count operations:
count; count_if;
• Heap operators: manipulating a max-heap:
make_heap; pop_heap; push_heap; sort_heap;
• Initializers: initializing data:
fill; fill_n; generate; generate_n;
• Operators: performing arithmetic operations of some sort:
accumulate; adjacent_difference; inner_product; partial_sum;
• Searchers: performing search (and find) operations:
adjacent_find; binary_search; equal_range; find; find_end; find_first_of; find_if;
lower_bound; max_element; min_element; search; search_n; set_difference;
set_intersection;
set_symmetric_difference; set_union; upper_bound;
• Shufflers: performing reordering operations (sorting, merging, permuting, shuffling, swapping):
inplace_merge; iter_swap; merge; next_permutation; nth_element; partial_sort; partial_
sort_copy; partition; prev_permutation; random_shuffle; remove; remove_copy;
remove_copy_if; remove_if; reverse; reverse_copy; rotate; rotate_copy; sort; stable_
partition; stable_sort; swap; unique;
• Visitors: visiting elements in a range:
for_each; replace; replace_copy; replace_copy_if; replace_if; transform; unique_copy;
19.1. THE GENERIC ALGORITHMS 537
19.1.1 accumulate
• Header file: <numeric>
• Function prototypes:
– Type accumulate(InputIterator first, InputIterator last, Type init);
– Type accumulate(InputIterator first, InputIterator last, Type init,
BinaryOperation op);
• Description:
– The first prototype: operator+ is applied to all elements implied by the iterator range
and to the initial value init. The resulting value is returned.
– The second prototype: the binary operator op is applied to all elements implied by the
iterator range and to the initial value init, and the resulting value is returned.
• Example:
#include <numeric>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int ia[] = {1, 2, 3, 4};
vector<int> iv(ia, ia + 4);
cout <<
"Sum of values: " << accumulate(iv.begin(), iv.end(), int()) <<
"\n"
"Product of values: " << accumulate(iv.begin(), iv.end(), int(1),
multiplies<int>()) << ’\n’;
}
/*
Displays:
Sum of values: 10
Product of values: 24
*/
19.1.2 adjacent_difference
• Header file: <numeric>
• Function prototypes:
– OutputIterator adjacent_difference(InputIterator first,
InputIterator last, OutputIterator result);
– OutputIterator adjacent_difference(InputIterator first,
InputIterator last, OutputIterator result, BinaryOperation op);
538 CHAPTER 19. THE STL GENERIC ALGORITHMS
• Description: All operations are performed on the original values, all computed values are returned
values.
– The first prototype: the first returned element is equal to the first element of the input
range. The remaining returned elements are equal to the difference of the corresponding
element in the input range and its previous element.
– The second prototype: the first returned element is equal to the first element of the input
range. The remaining returned elements are equal to the result of the binary operator op
applied to the corresponding element in the input range (left operand) and its previous
element (right operand).