Namespaces
Variants

std::ranges:: for_each, std::ranges:: for_each_result

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
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
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
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
Operations on uninitialized storage
Return types
Défini dans l'en-tête <algorithm>
Signature d'appel
template < std:: input_iterator I, std:: sentinel_for < I > S, class Proj = std:: identity ,

std:: indirectly_unary_invocable < std :: projected < I, Proj >> Fun >
constexpr for_each_result < I, Fun >

for_each ( I first, S last, Fun f, Proj proj = { } ) ;
(1) (depuis C++20)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirectly_unary_invocable <
std :: projected < ranges:: iterator_t < R > , Proj >> Fun >
constexpr for_each_result < ranges:: borrowed_iterator_t < R > , Fun >

for_each ( R && r, Fun f, Proj proj = { } ) ;
(2) (depuis C++20)
Types auxiliaires
template < class I, class F >
using for_each_result = ranges:: in_fun_result < I, F > ;
(3) (depuis C++20)
1) Applique l'objet fonction donné f au résultat de la valeur projetée par chaque itérateur dans la plage [ first , last ) , dans l'ordre.
2) Identique à (1) , mais utilise r comme plage source, comme si on utilisait ranges:: begin ( r ) comme first et ranges:: end ( r ) comme last .

Pour les deux surcharges, si le type d'itérateur est mutable, f peut modifier les éléments de la plage via l'itérateur déréférencé. Si f retourne un résultat, ce résultat est ignoré.

Les entités de type fonction décrites sur cette page sont des algorithm function objects (informellement appelées niebloids ), c'est-à-dire :

Table des matières

Paramètres

first, last - la paire itérateur-sentinelle définissant l'intervalle des éléments auxquels appliquer la fonction
r - l'intervalle des éléments auxquels appliquer la fonction
f - la fonction à appliquer à l'intervalle projeté
proj - projection à appliquer aux éléments

Valeur de retour

{ ranges:: next ( std :: move ( first ) , last ) , std :: move ( f ) }

Complexité

Exactement ranges:: distance ( first, last ) applications de f et proj .

Implémentation possible

struct for_each_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<I, Proj>> Fun>
    constexpr ranges::for_each_result<I, Fun>
        operator()(I first, S last, Fun f, Proj proj = {}) const
    {
        for (; first != last; ++first)
            std::invoke(f, std::invoke(proj, *first));
        return {std::move(first), std::move(f)};
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<ranges::iterator_t<R>,
             Proj>> Fun>
    constexpr ranges::for_each_result<ranges::borrowed_iterator_t<R>, Fun>
        operator()(R&& r, Fun f, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(f), std::ref(proj));
    }
};
inline constexpr for_each_fn for_each;

Exemple

L'exemple suivant utilise une expression lambda pour incrémenter tous les éléments d'un vecteur, puis utilise un operator() surchargé dans un foncteur pour calculer leur somme. Notez que pour calculer la somme, il est recommandé d'utiliser l'algorithme dédié std::accumulate .

#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Sum
{
    void operator()(int n) { sum += n; }
    int sum {0};
};
int main()
{
    std::vector<int> nums {3, 4, 2, 8, 15, 267};
    auto print = [](const auto& n) { std::cout << ' ' << n; };
    namespace ranges = std::ranges;
    std::cout << "before:";
    ranges::for_each(std::as_const(nums), print);
    print('\n');
    ranges::for_each(nums, [](int& n) { ++n; });
    // calls Sum::operator() for each number
    auto [i, s] = ranges::for_each(nums.begin(), nums.end(), Sum());
    assert(i == nums.end());
    std::cout << "after: ";
    ranges::for_each(nums.cbegin(), nums.cend(), print);
    std::cout << "\n" "sum: " << s.sum << '\n';
    using pair = std::pair<int, std::string>; 
    std::vector<pair> pairs {{1,"one"}, {2,"two"}, {3,"tree"}};
    std::cout << "project the pair::first: ";
    ranges::for_each(pairs, print, [](const pair& p) { return p.first; });
    std::cout << "\n" "project the pair::second:";
    ranges::for_each(pairs, print, &pair::second);
    print('\n');
}

Sortie :

before: 3 4 2 8 15 267 
after:  4 5 3 9 16 268
sum: 305
project the pair::first:  1 2 3
project the pair::second: one two tree

Voir aussi

boucle for sur plage (C++11) exécute une boucle sur une plage
applique une fonction à une plage d'éléments
(objet fonction algorithme)
applique un objet fonction aux N premiers éléments d'une séquence
(objet fonction algorithme)
applique un objet fonction unaire aux éléments d'une plage
(modèle de fonction)