이름공간
변수
행위

std::for_each

cppreference.com
< cpp‎ | algorithm
 
 
 
<algorithm> 에 정의되어 있음.
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

주어진 함수 객체 f를 범위 [first, last)안의 역참조되는 모든 iterator값에 순서대로 적용한다.

만약 InputIt가 수정가능한 iterator라면, f는 역참조된 iterator를 지나면서 범위값을 수정할지도 모른다. 만약 f가 어떤 값을 반환한다면, 그 값은 무시된다.

목차

[편집] 파라미터

first, last-함수가 적용될 범위
f-함수 객체, [first, last)범위안의 역참조되는 모든 iterator값에 적용된다

함수의 인자 형식(signature)은 다음과 같아야 한다 :

 void fun(const Type &a);

인자 형식이 const &일 필요는 없다.
The type Type must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type.

형식의 필요조건
-
InputIt 는 다음 조건을 만족해야 한다 : InputIterator.
-
UnaryFunction 는 다음 조건을 만족해야 한다 : MoveConstructible. CopyConstructible일 필요는 없다.

[편집] 반환값

f(until C++11)
std::move(f)(since C++11)

[편집] 복잡도

정확하게 flast - first만큼 이용된다.

[편집] 가능한 구현

template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
    for (; first != last; ++first) {
        f(*first);
    }
    return f;
}

[편집] 예제

아래 예제는 벡터의 모든 요소를 증가시키기 위해 lambda function를 사용한 후에 그것들의 누적값을 계산하기 위해 functor 에서 재정의된 operator()를 사용한다 :

#include <vector>
#include <algorithm>
#include <iostream>
 
struct Sum {
    Sum() { sum = 0; }
    void operator()(int n) { sum += n; }
 
    int sum;
};
 
int main()
{
    std::vector<int> nums{3, 4, 2, 9, 15, 267};
 
    std::cout << "before:";
    for (auto n : nums) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
 
    std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
 
    // 각 숫자마다 Sum::operator()를 호출
    Sum s = std::for_each(nums.begin(), nums.end(), Sum());
 
    std::cout << "after: ";
    for (auto n : nums) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
    std::cout << "sum: " << s.sum << '\n';
}

Output:

before: 3 4 2 9 15 267
after:  4 5 3 10 16 268
sum: 306

[편집] See also

틀:cpp/experimental/parallelism/dsc for each틀:cpp/experimental/parallelism/dsc for each n
applies a function to a range of elements
(function template) [edit]
range-for loopexecutes loop over range (since C++11) [edit]