1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
18 // { dg-do run { target c++20 } }
22 #include <testsuite_hooks.h>
23 #include <testsuite_iterators.h>
25 using __gnu_test::test_container
;
26 using __gnu_test::test_range
;
27 using __gnu_test::input_iterator_wrapper
;
28 using __gnu_test::forward_iterator_wrapper
;
29 using __gnu_test::random_access_iterator_wrapper
;
31 namespace ranges
= std::ranges
;
46 X x
[] = { {2}, {4}, {6}, {8}, {10}, {11} };
48 auto res
= ranges::for_each(x
, x
+6, f
, &X::i
);
49 VERIFY( res
.in
== x
+6 );
50 VERIFY( res
.fun
== &f
);
53 test_container
<X
, forward_iterator_wrapper
> c(x
);
55 ranges::for_each(c
, [&p
](int i
) { ++p
; }, &X::i
);
58 test_range
<X
, input_iterator_wrapper
> r(x
);
60 ranges::for_each(r
, [&q
](X
&) { ++q
; });
64 struct Y
{ int i
; int j
; };
71 Y y
[] = { {1,2}, {2,4}, {3,6} };
73 ranges::for_each(y
, [&a
](int i
) { a
+= i
; }, &Y::i
);
76 static_assert(f() == 6);
79 template<template<typename
> typename wrapper
>
83 int x
[] = {1,2,3,4,5};
84 test_range
<int, wrapper
> rx(x
);
86 auto func
= [&s
](int i
){ s
+= i
; };
87 auto [i
,f
] = ranges::for_each_n(rx
.begin(), 3, func
);
88 VERIFY( i
.ptr
= x
+3 );
91 VERIFY( s
== 1+2+3+1 );
95 auto [j
,g
] = ranges::for_each_n(rx
.begin(), -1, func
);
103 auto [k
,h
] = ranges::for_each_n(rx
.begin(), 5, func
, std::negate
<>{});
104 VERIFY( k
.ptr
== x
+5 );
105 VERIFY( s
== -(1+2+3+4+5) );
107 VERIFY( s
== -(1+2+3+4+5+6) );
113 int x
[] = {1,2,3,4,5};
115 ranges::for_each_n(x
+1, 4, [&p
](int i
){ p
*=i
; }, [](int i
){ return i
+1; });
124 test03
<input_iterator_wrapper
>();
125 test03
<random_access_iterator_wrapper
>();
126 static_assert(test04());