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