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// <algorithm>
10// UNSUPPORTED: c++03, c++11, c++14
11
12// template<class InputIterator, class Size, class Function>
13// constexpr InputIterator // constexpr after C++17
14// for_each_n(InputIterator first, Size n, Function f);
15
16
17#include <algorithm>
18#include <cassert>
19#include <functional>
20
21#include "test_macros.h"
22#include "test_iterators.h"
23
24#if TEST_STD_VER > 17
25TEST_CONSTEXPR bool test_constexpr() {
26 int ia[] = {1, 3, 6, 7};
27 int expected[] = {3, 5, 8, 9};
28 const std::size_t N = 4;
29
30 auto it = std::for_each_n(std::begin(ia), N, [](int &a) { a += 2; });
31 return it == (std::begin(ia) + N)
32 && std::equal(std::begin(ia), std::end(ia), std::begin(expected))
33 ;
34 }
35#endif
36
37struct for_each_test
38{
39 for_each_test(int c) : count(c) {}
40 int count;
41 void operator()(int& i) {++i; ++count;}
42};
43
44int main(int, char**)
45{
46 typedef cpp17_input_iterator<int*> Iter;
47 int ia[] = {0, 1, 2, 3, 4, 5};
48 const unsigned s = sizeof(ia)/sizeof(ia[0]);
49
50 {
51 auto f = for_each_test(0);
52 Iter it = std::for_each_n(first: Iter(ia), n: 0, f: std::ref(t&: f));
53 assert(it == Iter(ia));
54 assert(f.count == 0);
55 }
56
57 {
58 auto f = for_each_test(0);
59 Iter it = std::for_each_n(first: Iter(ia), n: s, f: std::ref(t&: f));
60
61 assert(it == Iter(ia+s));
62 assert(f.count == s);
63 for (unsigned i = 0; i < s; ++i)
64 assert(ia[i] == static_cast<int>(i+1));
65 }
66
67 {
68 auto f = for_each_test(0);
69 Iter it = std::for_each_n(first: Iter(ia), n: 1, f: std::ref(t&: f));
70
71 assert(it == Iter(ia+1));
72 assert(f.count == 1);
73 for (unsigned i = 0; i < 1; ++i)
74 assert(ia[i] == static_cast<int>(i+2));
75 }
76
77#if TEST_STD_VER > 17
78 static_assert(test_constexpr());
79#endif
80
81 return 0;
82}
83

source code of libcxx/test/std/algorithms/alg.nonmodifying/alg.foreach/for_each_n.pass.cpp