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-no-concepts
11 // UNSUPPORTED: gcc-10
12 
13 // Some basic examples of how transform_view might be used in the wild. This is a general
14 // collection of sample algorithms and functions that try to mock general usage of
15 // this view.
16 
17 #include <ranges>
18 
19 #include <cctype>
20 #include <functional>
21 #include <list>
22 #include <numeric>
23 #include <string>
24 #include <vector>
25 
26 #include <cassert>
27 #include "test_macros.h"
28 #include "test_iterators.h"
29 #include "types.h"
30 
31 template<std::ranges::range R>
32 auto toUpper(R range) {
33   return std::ranges::transform_view(range, [](char c) { return std::toupper(c); });
34 }
35 
36 unsigned badRandom() { return 42; }
37 
38 template<std::ranges::range R, class Fn = std::plus<std::iter_value_t<R>>>
39 auto withRandom(R&& range, Fn func = Fn()) {
40   return std::ranges::transform_view(range, std::bind_front(func, badRandom()));
41 }
42 
43 template<class E1, class E2, size_t N, class Join = std::plus<E1>>
44 auto joinArrays(E1 (&a)[N], E2 (&b)[N], Join join = Join()) {
45   return std::ranges::transform_view(a, [&a, &b, join](auto& x) {
46     auto idx = (&x) - a;
47     return join(x, b[idx]);
48   });
49 }
50 
51 int main(int, char**) {
52   {
53     std::vector vec = {1, 2, 3, 4};
54     auto sortOfRandom = withRandom(vec);
55     std::vector check = {43, 44, 45, 46};
56     assert(std::equal(sortOfRandom.begin(), sortOfRandom.end(), check.begin(), check.end()));
57   }
58 
59   {
60     int a[4] = {1, 2, 3, 4};
61     int b[4] = {4, 3, 2, 1};
62     auto out = joinArrays(a, b);
63     int check[4] = {5, 5, 5, 5};
64     assert(std::equal(out.begin(), out.end(), check));
65   }
66 
67   {
68     std::string_view str = "Hello, World.";
69     auto upp = toUpper(str);
70     std::string_view check = "HELLO, WORLD.";
71     assert(std::equal(upp.begin(), upp.end(), check.begin(), check.end()));
72   }
73 
74   return 0;
75 }
76