libcxx

libcxx mirror with random patches
git clone https://git.neptards.moe/neptards/libcxx.git
Log | Files | Refs

for_each_n.pass.cpp (2024B)


      1 //===----------------------------------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is dual licensed under the MIT and the University of Illinois Open
      6 // Source Licenses. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 // <algorithm>
     11 // UNSUPPORTED: c++98, c++03, c++11, c++14
     12 
     13 // template<class InputIterator, class Size, class Function>
     14 //    constexpr InputIterator      // constexpr after C++17
     15 //    for_each_n(InputIterator first, Size n, Function f);
     16 
     17 
     18 #include <algorithm>
     19 #include <cassert>
     20 
     21 #include "test_macros.h"
     22 #include "test_iterators.h"
     23 
     24 #if TEST_STD_VER > 17
     25 TEST_CONSTEXPR bool test_constexpr() {
     26     int ia[] = {1, 3, 6, 7};
     27     int expected[] = {3, 5, 8, 9};
     28     const 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 
     37 struct for_each_test
     38 {
     39     for_each_test(int c) : count(c) {}
     40     int count;
     41     void operator()(int& i) {++i; ++count;}
     42 };
     43 
     44 int main()
     45 {
     46     typedef 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(Iter(ia), 0, std::ref(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(Iter(ia), s, std::ref(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(Iter(ia), 1, std::ref(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 }