Most of the algorithms are defined in the algorithm
header. The library also defines a set of generic numeric algorithms that are defined in the numeric
header.
In general, the algorithms do not work directly on a container. Instead, they operate by traversing a range of elements bounded by two iterators (§ 9.2.1, p. 331). Typically, as the algorithm traverses the range, it does something with each element. For example, suppose we have a vector
of int
s and we want to know if that vector
holds a particular value. The easiest way to answer this question is to call the library find
algorithm:
int val = 42; // value we'll look for
// result will denote the element we want if it's in vec, or vec.cend() if not
auto result = find(vec.cbegin(), vec.cend(), val);
// report the result
cout << "The value " << val
<< (result == vec.cend()
? " is not present" : " is present") << endl;
The first two arguments to find
are iterators denoting a range of elements, and the third argument is a value. find
compares each element in the given range to the given value. It returns an iterator to the first element that is equal to that value. If there is no match, find
returns its second iterator to indicate failure. Thus, we can determine whether the element was found by comparing the return value with the second iterator argument. We do this test in the output statement, which uses the conditional operator (§ 4.7, p. 151) to report whether the value was found.
Because find
operates in terms of iterators, we can use the same find
function to look for values in any type of container. For example, we can use find
to look for a value in a list
of string
s:
string val = "a value"; // value we'll look for
// this call to find looks through string elements in a list
auto result = find(1st.cbegin(), 1st.cend(), val);
Similarly, because pointers act like iterators on built-in arrays, we can use find
to look in an array:
int ia[] = {27, 210, 12, 47, 109, 83};
int val = 83;
int* result = find(begin(ia), end(ia), val);
Here we use the library begin
and end
functions (§ 3.5.3, p. 118) to pass a pointer to the first and one past the last elements in ia
.
We can also look in a subrange of the sequence by passing iterators (or pointers) to the first and one past the last element of that subrange. For example, this call looks for a match in the elements ia[1], ia[2]
, and ia[3]
:
// search the elements starting from ia[1] up to but not including ia[4]
auto result = find(ia + 1, ia + 4, val);