Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there and neat equivalent to view a member function/variable?

Streams library has a neat map function to view a range by a member function. Is there any equivalent view in Range-V3?

Would view::transform be the only option?

like image 309
Viktor Sehr Avatar asked Mar 16 '23 17:03

Viktor Sehr


1 Answers

The example from the article:

std::vector widgets = /* ... */    
std::set ids = stream::MakeStream::from(widgets)
         .map(&Widget::getId)
         .to_set();

(ignoring the missing template arguments for std::vector and std::set) in ranges-v3 would be:

std::vector<Widget> widgets = // ...
std::set<Widget::ID> ids = widgets | ranges::view::transform(&Widget::getId);

Yes, transform is the equivalent to map in Streams.

All the algorithms in range-v3 accept Invokable Projections that allow enable the algorithm to select range elements on the basis of a transformation, but still operate on the entire element. For example, we can sort the Widgets by their IDs:

widgets |= ranges::action::sort(std::greater<Widget::ID>{}, &Widget::getId);
like image 157
Casey Avatar answered May 10 '23 10:05

Casey