C++ for_each
C++ for_each
Define
Defined in header <algorithm> | ||
(1) | ||
template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); | (until C++20) | |
template< class InputIt, class UnaryFunction > constexpr UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); | (since C++20) | |
template< class ExecutionPolicy, class ForwardIt, class UnaryFunction2 > void for_each( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryFunction2 f ); | (2) | (since C++17) |
Example:
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> nums{1,2,3,4,5,6,7}; int myNum = 0; std::for_each(nums.begin(), nums.end(), [&](int n) { myNum = n; //can access by [&] std::cout << myNum << " "; } ); return 0; }
Output : 1 2 3 4 5 6 7
for_each의 첫 번째 인자는 시작, 두번째 인자는 끝, 세번째 인자로는 시작부터 끝까지 할 동작을 함수로 정의한다.
댓글
댓글 쓰기