xref: /llvm-project/libcxx/test/std/algorithms/alg.nonmodifying/alg.count/count.pass.cpp (revision 164c204a19f7859d570003d4c5e82faf48cb65a9)
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 
11 // template<InputIterator Iter, class T>
12 //   requires HasEqualTo<Iter::value_type, T>
13 //   constexpr Iter::difference_type   // constexpr after C++17
14 //   count(Iter first, Iter last, const T& value);
15 
16 // ADDITIONAL_COMPILE_FLAGS(has-fconstexpr-steps): -fconstexpr-steps=20000000
17 // ADDITIONAL_COMPILE_FLAGS(has-fconstexpr-ops-limit): -fconstexpr-ops-limit=70000000
18 
19 #include <algorithm>
20 #include <cassert>
21 #include <vector>
22 
23 #include "test_macros.h"
24 #include "test_iterators.h"
25 #include "type_algorithms.h"
26 
27 struct Test {
28   template <class Iter>
29   TEST_CONSTEXPR_CXX20 void operator()() {
30     int ia[]          = {0, 1, 2, 2, 0, 1, 2, 3};
31     const unsigned sa = sizeof(ia) / sizeof(ia[0]);
32     assert(std::count(Iter(ia), Iter(ia + sa), 2) == 3);
33     assert(std::count(Iter(ia), Iter(ia + sa), 7) == 0);
34     assert(std::count(Iter(ia), Iter(ia), 2) == 0);
35   }
36 };
37 
38 TEST_CONSTEXPR_CXX20 bool test() {
39   types::for_each(types::cpp17_input_iterator_list<const int*>(), Test());
40 
41   if (TEST_STD_AT_LEAST_20_OR_RUNTIME_EVALUATED) {
42     std::vector<bool> vec(256 + 64);
43     for (ptrdiff_t i = 0; i != 256; ++i) {
44       for (size_t offset = 0; offset != 64; ++offset) {
45         std::fill(vec.begin(), vec.end(), false);
46         std::fill(vec.begin() + offset, vec.begin() + i + offset, true);
47         assert(std::count(vec.begin() + offset, vec.begin() + offset + 256, true) == i);
48         assert(std::count(vec.begin() + offset, vec.begin() + offset + 256, false) == 256 - i);
49       }
50     }
51   }
52 
53   return true;
54 }
55 
56 int main(int, char**) {
57   test();
58 #if TEST_STD_VER >= 20
59   static_assert(test());
60 #endif
61 
62   return 0;
63 }
64