Algorithms

Non-mutating algorithms

for_each

Category: algorithms

Component type: function

Prototype

template <class InputIterator, class UnaryFunction>

UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);

Description

For_each applies the function object f to each element in the range [first, last); f's return value, if any, is ignored. Applications are performed in forward order, i.e. from first to last. For_each returns the function object after it has been applied to each element. [1]

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

• InputIterator is a model of Input Iterator

• UnaryFunction is a model of Unary Function

• UnaryFunction does not apply any non-constant operation through its argument.

• InputIterator's value type is convertible to UnaryFunction 's argument type.

Preconditions

• [first, last) is a valid range.

Complexity

Linear. Exactly last – first applications of UnaryFunction.

Example

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;

}

Notes

[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.

See also

The function object overview, count, copy

find

Category: algorithms

Component type: function

Prototype

template<class InputIterator, class EqualityComparable>

InputIterator find(InputIterator first, InputIterator last, const EqualityComparable& value);

Description

Returns the first iterator i in the range [first, last) such that *i == value. Returns last if no such iterator exists.

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

• 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.

Preconditions

• [first, last) is a valid range.

Complexity

Linear: at most last – first comparisons for equality.

Example

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);

See also

find_if.

find_if

Category: algorithms

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату