xref: /freebsd/contrib/llvm-project/libcxx/include/__algorithm/min_element.h (revision 401ab69cff8fa2320a9f8ea4baa114a6da6c952b)
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_MIN_ELEMENT_H
10 #define _LIBCPP___ALGORITHM_MIN_ELEMENT_H
11 
12 #include <__algorithm/comp.h>
13 #include <__algorithm/comp_ref_type.h>
14 #include <__config>
15 #include <__functional/identity.h>
16 #include <__functional/invoke.h>
17 #include <__iterator/iterator_traits.h>
18 #include <__type_traits/is_callable.h>
19 #include <__utility/move.h>
20 
21 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22 #  pragma GCC system_header
23 #endif
24 
25 _LIBCPP_BEGIN_NAMESPACE_STD
26 
27 template <class _Comp, class _Iter, class _Sent, class _Proj>
28 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14
29 _Iter __min_element(_Iter __first, _Sent __last, _Comp __comp, _Proj& __proj) {
30   if (__first == __last)
31     return __first;
32 
33   _Iter __i = __first;
34   while (++__i != __last)
35     if (std::__invoke(__comp, std::__invoke(__proj, *__i), std::__invoke(__proj, *__first)))
36       __first = __i;
37 
38   return __first;
39 }
40 
41 template <class _Comp, class _Iter, class _Sent>
42 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14
43 _Iter __min_element(_Iter __first, _Sent __last, _Comp __comp) {
44   auto __proj = __identity();
45   return std::__min_element<_Comp>(std::move(__first), std::move(__last), __comp, __proj);
46 }
47 
48 template <class _ForwardIterator, class _Compare>
49 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
50 min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
51 {
52   static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
53       "std::min_element requires a ForwardIterator");
54   static_assert(__is_callable<_Compare, decltype(*__first), decltype(*__first)>::value,
55               "The comparator has to be callable");
56 
57   return std::__min_element<__comp_ref_type<_Compare> >(std::move(__first), std::move(__last), __comp);
58 }
59 
60 template <class _ForwardIterator>
61 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _ForwardIterator
62 min_element(_ForwardIterator __first, _ForwardIterator __last)
63 {
64     return _VSTD::min_element(__first, __last,
65               __less<typename iterator_traits<_ForwardIterator>::value_type>());
66 }
67 
68 _LIBCPP_END_NAMESPACE_STD
69 
70 #endif // _LIBCPP___ALGORITHM_MIN_ELEMENT_H
71