Skip to content

Commit 031e1bf

Browse files
author
Patrick Palka
committed
libstdc++: Fix complexity of drop_view::begin() const [PR112641]
Views are required to have a amortized O(1) begin(), but our drop_view's const begin overload is O(n) for non-common ranges with a non-sized sentinel. This patch reimplements it so that it's O(1) always. See also LWG 4009. PR libstdc++/112641 libstdc++-v3/ChangeLog: * include/std/ranges (drop_view::begin): Reimplement const overload so that it's O(1) always. * testsuite/std/ranges/adaptors/drop.cc (test10): New test. Reviewed-by: Jonathan Wakely <[email protected]> (cherry picked from commit 7f622ee)
1 parent d2e2688 commit 031e1bf

File tree

2 files changed

+14
-2
lines changed
  • libstdc++-v3

2 files changed

+14
-2
lines changed

libstdc++-v3/include/std/ranges

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2530,8 +2530,8 @@ namespace views::__adaptor
25302530
begin() const
25312531
requires random_access_range<const _Vp> && sized_range<const _Vp>
25322532
{
2533-
return ranges::next(ranges::begin(_M_base), _M_count,
2534-
ranges::end(_M_base));
2533+
return ranges::begin(_M_base) + ranges::min(ranges::distance(_M_base),
2534+
_M_count);
25352535
}
25362536

25372537
constexpr auto

libstdc++-v3/testsuite/std/ranges/adaptors/drop.cc

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,17 @@ test09()
275275
static_assert(!requires { views::all | drop; });
276276
}
277277

278+
constexpr bool
279+
test10()
280+
{
281+
// PR libstdc++/112641 - drop_view::begin const may have O(n) complexity
282+
const auto s = ranges::subrange(views::iota(size_t(1)), size_t(-1));
283+
const auto r = ranges::drop_view(s, s.size() - 1);
284+
const auto b = r.begin(); // time out
285+
VERIFY( *b == size_t(-1) );
286+
return true;
287+
}
288+
278289
int
279290
main()
280291
{
@@ -287,4 +298,5 @@ main()
287298
test07();
288299
test08();
289300
test09();
301+
static_assert(test10());
290302
}

0 commit comments

Comments
 (0)