std::for_each_n

Header: <algorithm>

Applies the given function object f to the result of dereferencing every iterator in the range [first,first + n). If f returns a result, the result is ignored.

# Declarations

template< class InputIt, class Size, class UnaryFunc >
InputIt for_each_n( InputIt first, Size n, UnaryFunc f );

(since C++17) (constexpr since C++20)

template< class ExecutionPolicy,
class ForwardIt, class Size, class UnaryFunc >
ForwardIt for_each_n( ExecutionPolicy&& policy,
ForwardIt first, Size n, UnaryFunc f );

(since C++17)

# Parameters

# Return value

An iterator equal to first + n, or more formally, to std::advance(first, n).

# Example

#include <algorithm>
#include <iostream>
#include <vector>
 
void println(auto const& v)
{
    for (auto count{v.size()}; const auto& e : v)
        std::cout << e << (--count ? ", " : "\n");
}
 
int main()
{
    std::vector<int> vi{1, 2, 3, 4, 5};
    println(vi);
 
    std::for_each_n(vi.begin(), 3, [](auto& n) { n *= 2; });
    println(vi);
}

# See also