xref: /freebsd/contrib/llvm-project/libcxx/include/__algorithm/partition.h (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
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_PARTITION_H
10 #define _LIBCPP___ALGORITHM_PARTITION_H
11 
12 #include <__config>
13 #include <__iterator/iterator_traits.h>
14 #include <__utility/swap.h>
15 
16 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
17 #pragma GCC system_header
18 #endif
19 
20 _LIBCPP_BEGIN_NAMESPACE_STD
21 
22 template <class _Predicate, class _ForwardIterator>
23 _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
24 __partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, forward_iterator_tag)
25 {
26     while (true)
27     {
28         if (__first == __last)
29             return __first;
30         if (!__pred(*__first))
31             break;
32         ++__first;
33     }
34     for (_ForwardIterator __p = __first; ++__p != __last;)
35     {
36         if (__pred(*__p))
37         {
38             swap(*__first, *__p);
39             ++__first;
40         }
41     }
42     return __first;
43 }
44 
45 template <class _Predicate, class _BidirectionalIterator>
46 _LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator
47 __partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
48             bidirectional_iterator_tag)
49 {
50     while (true)
51     {
52         while (true)
53         {
54             if (__first == __last)
55                 return __first;
56             if (!__pred(*__first))
57                 break;
58             ++__first;
59         }
60         do
61         {
62             if (__first == --__last)
63                 return __first;
64         } while (!__pred(*__last));
65         swap(*__first, *__last);
66         ++__first;
67     }
68 }
69 
70 template <class _ForwardIterator, class _Predicate>
71 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
72 _ForwardIterator
73 partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
74 {
75     return _VSTD::__partition<_Predicate&>(
76         __first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
77 }
78 
79 _LIBCPP_END_NAMESPACE_STD
80 
81 #endif // _LIBCPP___ALGORITHM_PARTITION_H
82