1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // UNSUPPORTED: c++03, c++11, c++14, c++17 10 // UNSUPPORTED: libcpp-has-no-incomplete-ranges 11 12 // Some basic examples of how drop_view might be used in the wild. This is a general 13 // collection of sample algorithms and functions that try to mock general usage of 14 // this view. 15 16 #include <ranges> 17 18 #include <vector> 19 #include <list> 20 #include <string> 21 22 #include <cassert> 23 #include "test_macros.h" 24 #include "test_iterators.h" 25 #include "types.h" 26 27 template<class T> 28 concept ValidDropView = requires { typename std::ranges::drop_view<T>; }; 29 30 static_assert( ValidDropView<MoveOnlyView>); 31 static_assert(!ValidDropView<Range>); 32 33 static_assert(!std::ranges::enable_borrowed_range<std::ranges::drop_view<MoveOnlyView>>); 34 static_assert( std::ranges::enable_borrowed_range<std::ranges::drop_view<BorrowableView>>); 35 36 template<std::ranges::view View> 37 bool orderedFibonacci(View v, int n = 1) { 38 if (v.size() < 3) 39 return true; 40 41 if (v[2] != v[0] + v[1]) 42 return false; 43 44 return orderedFibonacci(std::ranges::drop_view(v.base(), n), n + 1); 45 } 46 47 template<std::ranges::view View> 48 std::ranges::view auto makeEven(View v) { 49 return std::ranges::drop_view(v, v.size() % 2); 50 } 51 52 template<std::ranges::view View, class T> 53 int indexOf(View v, T element) { 54 int index = 0; 55 for (auto e : v) { 56 if (e == element) 57 return index; 58 index++; 59 } 60 return -1; 61 } 62 63 template<std::ranges::view View, class T> 64 std::ranges::view auto removeBefore(View v, T element) { 65 std::ranges::drop_view out(v, indexOf(v, element) + 1); 66 return View(out.begin(), out.end()); 67 } 68 69 template<> 70 constexpr bool std::ranges::enable_view<std::vector<int>> = true; 71 72 template<> 73 constexpr bool std::ranges::enable_view<std::list<int>> = true; 74 75 template<> 76 constexpr bool std::ranges::enable_view<std::string> = true; 77 78 int main(int, char**) { 79 const std::vector vec = {1,1,2,3,5,8,13}; 80 assert(orderedFibonacci(std::ranges::drop_view(vec, 0))); 81 const std::vector vec2 = {1,1,2,3,5,8,14}; 82 assert(!orderedFibonacci(std::ranges::drop_view(vec2, 0))); 83 84 const std::list l = {1, 2, 3}; 85 auto el = makeEven(l); 86 assert(el.size() == 2); 87 assert(*el.begin() == 2); 88 89 const std::string s = "Hello, World"; 90 assert(removeBefore(s, ' ') == "World"); 91 92 return 0; 93 } 94