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