c++c++11boost-rangerange-v3

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?


Solution

  • 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);