Skip to content

<algorithm>: contains_subrange should not use std::distance #86833

Closed
@hewillk

Description

@hewillk

operator()(_Range1&& __range1, _Range2&& __range2, _Pred __pred = {}, _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) {
auto __n2 = 0;
if constexpr (sized_range<_Range2>) {
__n2 = ranges::size(__range2);
} else {
__n2 = std::distance(cbegin(__range2), cend(__range2));
}
if (__n2 == 0)
return true;

...because it is based on the C++17 iterator model rather than the C++20 Ranges iterator model.
In addition, __n2 is an integer type and may not accommodate difference_type.
I believe the above can be just simplified to:

if (ranges::distance(__range2) == 0)
  return true;

testcase:

#include <ranges>
#include <algorithm>

static_assert(
  std::ranges::contains_subrange(
    std::views::iota(0, 5),
    std::views::iota(0, 5) | std::views::filter([](int i) { return true; }) )
);

https://godbolt.org/z/G6oMoM5Wz

Metadata

Metadata

Assignees

No one assigned

    Labels

    libc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions