◐ Shell
reader mode source ↗
From cppreference.com
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Non-modifying sequence operations    
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
(C++11)    

Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations


 
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
       
       
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
       
       
Permutation operations
Fold operations
Numeric operations
(C++23)            
Operations on uninitialized storage
Return types
 
Defined in header <algorithm>
Call signature
template< std::input_iterator I, class Proj = std::identity,
          std::indirectly_unary_invocable<std::projected<I, Proj>> Fun >
constexpr for_each_n_result<I, Fun>
    for_each_n( I first, std::iter_difference_t<I> count,
                Fun f, Proj proj = {} );
(1) (since C++20)
template< /*execution-policy*/ Ep,
          std::random_access_iterator I, class Proj = identity,
          std::indirectly_unary_invocable<std::projected<I, Proj>> Fun >
I for_each_n( Ep&& policy, I first, iter_difference_t<I> count,
              Fun f, Proj proj = {} );
(2) (since C++26)
Helper types
template< class I, class F >
using for_each_n_result = ranges::in_fun_result<I, F>;
(3) (since C++20)

For the definition of /*execution-policy*/, see this page.

Applies the given invocable object f to each element (projected by proj) in the target range [firstranges::next(first, count)). If f returns a result, the result is ignored.

1) f is applied in order from first.
2) f might not be applied in order. The algorithm is executed according to policy.
Unlike other parallel algorithms, for_each_n is not allowed to make arbitrary copies of elements from the target range.

If count >= 0 is not true, the behavior is undefined.

The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:

Parameters

first - the beginning of the target range
count - the number of elements in the target range
f - the invocable object to be applied to the (projected) elements
proj - the projection to be applied to the elements
policy - the execution policy to use

Return value

1) {ranges::next(first, count), std::move(f)}
2) ranges::next(first, count)

Complexity

Exactly count applications of f and proj.

Exceptions

2) During the execution process:
  • If the temporary memory resources required for parallelization are not available, std::bad_alloc is thrown.
  • If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for standard policies, std::terminate is invoked).

Notes

If the projection returns a mutable reference, f may modify the elements in the target range.

Possible implementation

struct for_each_n_fn
{
    template<std::input_iterator I, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<I, Proj>> Fun>
    constexpr for_each_n_result<I, Fun>
        operator()(I first, std::iter_difference_t<I> count,
                   Fun fun, Proj proj = Proj{}) const
    {
        for (; count-- > 0; ++first)
            std::invoke(fun, std::invoke(proj, *first));
        return {std::move(first), std::move(fun)};
    }
};

inline constexpr for_each_n_fn for_each_n{};

Example

#include <algorithm>
#include <array>
#include <iostream>
#include <ranges>
#include <string_view>

struct P
{
    int first;
    char second;
    friend std::ostream& operator<<(std::ostream& os, const P& p)
    {
        return os << '{' << p.first << ",'" << p.second << "'}";
    }
};

auto print = [](std::string_view name, const auto& v)
{
    std::cout << name << ": ";
    for (auto n = v.size(); const auto& e : v)
        std::cout << e << (--n ? ", " : "\n");
};

int main()
{
    std::array a {1, 2, 3, 4, 5};
    print("a", a);
    // Negate first three numbers:
    std::ranges::for_each_n(a.begin(), 3, [](auto& n) { n *= -1; });
    print("a", a);
    
    std::array s { P{1,'a'}, P{2, 'b'}, P{3, 'c'}, P{4, 'd'} };
    print("s", s);
    // Negate data members “P::first” using projection:
    std::ranges::for_each_n(s.begin(), 2, [](auto& x) { x *= -1; }, &P::first);
    print("s", s);
    // Capitalize data members “P::second” using projection:
    std::ranges::for_each_n(s.begin(), 3, [](auto& c) { c -= 'a' - 'A'; }, &P::second);
    print("s", s);
}

Output:

a: 1, 2, 3, 4, 5
a: -1, -2, -3, 4, 5
s: {1,'a'}, {2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'a'}, {-2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'A'}, {-2,'B'}, {3,'C'}, {4,'d'}

See also

applies a function object to the first N elements of a sequence
(function template) [edit]
applies a unary function object to elements from a range
(function template & algorithm function object)[edit]
range-for loop(C++11) executes loop over range[edit]