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<ForwardIterator Iter, StrictWeakOrder<auto, Iter::value_type> Compare>
12// requires CopyConstructible<Compare>
13// Iter
14// max_element(Iter first, Iter last, Compare comp);
15
16#include <algorithm>
17#include <functional>
18#include <random>
19#include <cassert>
20
21#include "test_macros.h"
22#include "test_iterators.h"
23
24std::mt19937 randomness;
25
26template <class Iter>
27void
28test(Iter first, Iter last)
29{
30 Iter i = std::max_element(first, last, std::greater<int>());
31 if (first != last)
32 {
33 for (Iter j = first; j != last; ++j)
34 assert(!std::greater<int>()(*i, *j));
35 }
36 else
37 assert(i == last);
38}
39
40template <class Iter>
41void
42test(int N)
43{
44 int* a = new int[N];
45 for (int i = 0; i < N; ++i)
46 a[i] = i;
47 std::shuffle(first: a, last: a+N, g&: randomness);
48 test(Iter(a), Iter(a+N));
49 delete [] a;
50}
51
52template <class Iter>
53void
54test()
55{
56 test<Iter>(0);
57 test<Iter>(1);
58 test<Iter>(2);
59 test<Iter>(3);
60 test<Iter>(10);
61 test<Iter>(1000);
62}
63
64template <class Iter, class Pred>
65void test_eq0(Iter first, Iter last, Pred p)
66{
67 assert(first == std::max_element(first, last, p));
68}
69
70void test_eq()
71{
72 const int N = 10;
73 int* a = new int[N];
74 for (int i = 0; i < N; ++i)
75 a[i] = 10; // all the same
76 test_eq0(first: a, last: a+N, p: std::less<int>());
77 test_eq0(first: a, last: a+N, p: std::greater<int>());
78 delete [] a;
79}
80
81#if TEST_STD_VER >= 14
82constexpr int il[] = { 2, 4, 6, 8, 7, 5, 3, 1 };
83struct less { constexpr bool operator ()( const int &x, const int &y) const { return x < y; }};
84#endif
85
86void constexpr_test()
87{
88#if TEST_STD_VER >= 14
89 constexpr auto p = std::max_element(il, il+8, less());
90 static_assert ( *p == 8, "" );
91#endif
92}
93
94int main(int, char**)
95{
96 test<forward_iterator<const int*> >();
97 test<bidirectional_iterator<const int*> >();
98 test<random_access_iterator<const int*> >();
99 test<const int*>();
100 test_eq();
101
102 constexpr_test();
103
104 return 0;
105}
106

source code of libcxx/test/std/algorithms/alg.sorting/alg.min.max/max_element_comp.pass.cpp