std::for_each

cppreference.com

Example

Sum: @struct type = {
    operator(): (inout this, n: int) = { sum += n; }
    sum: int = 0;
}

main: () = {
    v: std::vector = (3, -4, 2, -8, 15, 267);
 
    printer:= :(n: int) = { std::cout << "(n)$ "; };
 
    std::cout << "before:\t";
    std::for_each(v.cbegin(), v.cend(), printer);
    std::cout << '\n';
 
    // increment elements in-place
    std::for_each(v.begin(), v.end(), :(inout n) = n++);
 
    std::cout << "after:\t";
    std::for_each(v.cbegin(), v.cend(), printer);
    std::cout << '\n';
 
    // invoke Sum::operator() for each element
    s: Sum = std::for_each(v.cbegin(), v.cend(), Sum());    
    std::cout << "sum:\t(s.sum)$\n";
}

Output

before:	3 -4 2 -8 15 267 
after:	4 -3 3 -7 16 268 
sum:	281

Back to top

cpp2reference.com licensed under CC-BY-SA and GFDL.