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 #ifndef _LIBCPP___ALGORITHM_MINMAX_H
10 #define _LIBCPP___ALGORITHM_MINMAX_H
11 
12 #include <__algorithm/comp.h>
13 #include <__config>
14 #include <initializer_list>
15 #include <utility>
16 
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 #pragma GCC system_header
19 #endif
20 
21 _LIBCPP_BEGIN_NAMESPACE_STD
22 
23 template<class _Tp, class _Compare>
24 _LIBCPP_NODISCARD_EXT inline
25 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
26 pair<const _Tp&, const _Tp&>
27 minmax(const _Tp& __a, const _Tp& __b, _Compare __comp)
28 {
29     return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) :
30                               pair<const _Tp&, const _Tp&>(__a, __b);
31 }
32 
33 template<class _Tp>
34 _LIBCPP_NODISCARD_EXT inline
35 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
36 pair<const _Tp&, const _Tp&>
37 minmax(const _Tp& __a, const _Tp& __b)
38 {
39     return _VSTD::minmax(__a, __b, __less<_Tp>());
40 }
41 
42 #ifndef _LIBCPP_CXX03_LANG
43 
44 template<class _Tp, class _Compare>
45 _LIBCPP_NODISCARD_EXT inline
46 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
47 pair<_Tp, _Tp>
48 minmax(initializer_list<_Tp> __t, _Compare __comp)
49 {
50     typedef typename initializer_list<_Tp>::const_iterator _Iter;
51     _Iter __first = __t.begin();
52     _Iter __last  = __t.end();
53     pair<_Tp, _Tp> __result(*__first, *__first);
54 
55     ++__first;
56     if (__t.size() % 2 == 0)
57     {
58         if (__comp(*__first,  __result.first))
59             __result.first  = *__first;
60         else
61             __result.second = *__first;
62         ++__first;
63     }
64 
65     while (__first != __last)
66     {
67         _Tp __prev = *__first++;
68         if (__comp(*__first, __prev)) {
69             if ( __comp(*__first, __result.first)) __result.first  = *__first;
70             if (!__comp(__prev, __result.second))  __result.second = __prev;
71             }
72         else {
73             if ( __comp(__prev, __result.first))    __result.first  = __prev;
74             if (!__comp(*__first, __result.second)) __result.second = *__first;
75             }
76 
77         __first++;
78     }
79     return __result;
80 }
81 
82 template<class _Tp>
83 _LIBCPP_NODISCARD_EXT inline
84 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
85 pair<_Tp, _Tp>
86 minmax(initializer_list<_Tp> __t)
87 {
88     return _VSTD::minmax(__t, __less<_Tp>());
89 }
90 
91 #endif // _LIBCPP_CXX03_LANG
92 
93 _LIBCPP_END_NAMESPACE_STD
94 
95 #endif // _LIBCPP___ALGORITHM_MINMAX_H
96