Sum:@structtype={operator():(inoutthis,n:int)={sum+=n;}sum:int=0;}main:()={nums:std::vector=(3,4,2,8,15,267);printer:=:(n)={std::cout<<" (n)$";};ranges:namespace==std::ranges;std::cout<<"before:";ranges::for_each(std::as_const(nums),printer);printer('\n');ranges::for_each(nums,:(inoutn:int)=n++);// calls Sum::operator() for each numberres:=ranges::for_each(nums.begin(),nums.end(),Sum());assert(res.in==nums.end());std::cout<<"after: ";ranges::for_each(nums.cbegin(),nums.cend(),printer);std::cout<<"\nsum: (res.fun.sum)$\n";pair:type==std::pair<int,std::string>;pairs:std::vector=(:pair=(1,"one"),:pair=(2,"two"),:pair=(3,"three"));std::cout<<"project the pair::first: ";ranges::for_each(pairs,printer,:(p:pair)->int={returnp.first;});std::cout<<"\nproject the pair::second:";ranges::for_each(pairs,printer,pair::second&);printer('\n');}
Output
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 three