Algorithms
Non-mutating algorithms
for_each
Category: algorithms
Component type: function
template <class InputIterator, class UnaryFunction>
UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);
Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.
Linear. Exactly
template<class T> struct print : public unary_function<T, void> {
print(ostream& out) : os(out), count(0) {}
void operator() (T x) { os << x << ' '; ++count; }
ostream& os;
int count;
};
int main() {
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
print<int> P = for_each(A, A + N, print<int>(cout));
cout << endl << P.count << ' objects printed.' << endl;
}
[1] This return value is sometimes useful, since a function object may have local state. It might, for example, count the number of times that it is called, or it might have a status flag to indicate whether or not a call succeeded.
The function object overview,
find
Category: algorithms
Component type: function
template<class InputIterator, class EqualityComparable>
InputIterator find(InputIterator first, InputIterator last, const EqualityComparable& value);
Returns the first iterator
Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.
• EqualityComparable is a model of EqualityComparable.
• InputIterator is a model of InputIterator.
• Equality is defined between objects of type EqualityComparable and objects of InputIterator's value type.
Linear: at most
list <int>L;
L.push_back(3);
L.push_back(1);
L.push_back(7);
list<int>::iterator result = find(L.begin(), L.end(), 7);
assert(result == L.end() || *result == 7);
find_if.
find_if
Category: algorithms
