'Can std::ranges be used with std::list

I note that many algorithms can be used with ranges allowing the use of members of custom types, rather than needing lambda functions. So, am curious whether std::ranges can be used efficiently with std::list<>. I am cognisant that std::list<> is not the go to data structure for such algorithms, but for other issues, it is the better for my purpose.



Solution 1:[1]

In C++20, different ranges can be subdivided into input_range, forward_range, bidirectional_range, random_access_range, and contiguous_range base on their iterator types. The more refinement of the range, the more operations it supports and the more efficient its performance.

std::list is a bidirectional_range, so any C++20 rangified algorithm that requires a bidirectional_range and below can be applied to it.

Take ranges::transform in <algorithm> as an example

template<ranges::input_range R, std::weakly_incrementable O,
         std::copy_constructible F, class Proj = std::identity>
  requires /* */
constexpr unary_transform_result<ranges::borrowed_iterator_t<R>, O>
transform(R&& r, O result, F op, Proj proj = {});

which explicitly requires that R must model input_range. Since std::list models a more refined bidirectional_range, it has all the operations supported by input_range and will work well with this algorithm.

Again, take the range adaptor ranges::transform_view in <ranges> as an example

template<ranges::input_range V, std::copy_constructible F>
  requires /* */
class transform_view : public ranges::view_interface<transform_view<V, F>>;

which only requires an input_range, so it can be used with std::list. It's worth noting that most range adaptors only require the underlying range to model input_range (only a few require forward_range), so std::list will also work well with them.

As for efficiency, since std::list only supports forward and backward operations, applying C++20 range utilities to it is less efficient than applying it to a random_access_range such as std::vector, but it definitely works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1