Apr 17, 2022

[C++][C++20][recipe] materialize a container from range view

auto to_vector(auto&& r) {
  std::vector<std::ranges::range_value_t<decltype(r)>> v;
  
  if constexpr(std::ranges::sized_range<decltype(r)>) {
    v.reserve(std::ranges::size(r));
  }
  
  std::ranges::copy(r, std::back_inserter(v));
  return v;
}
as for std::ranges::sort 
always materialized before using (view doesn't work while its lazy evaluated)
auto v = to_vector(odd_numbers);
std::ranges::sort(v);
However; as for std::views::take
returns the view with iterator preserved; thus could be used in std::ranges::sort
auto vec = std::vector{4, 2, 7, 1, 2, 6, 1, 5};
auto first_half = vec | std::views::take(vec.size() / 2);
std::ranges::sort(first_half);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.