xref: /freebsd/contrib/llvm-project/libcxx/include/__algorithm/next_permutation.h (revision 093cf790569775b80662926efea6d9d3464bde94)
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_NEXT_PERMUTATION_H
10 #define _LIBCPP___ALGORITHM_NEXT_PERMUTATION_H
11 
12 #include <__config>
13 #include <__algorithm/comp.h>
14 #include <__algorithm/comp_ref_type.h>
15 #include <__algorithm/reverse.h>
16 #include <__iterator/iterator_traits.h>
17 #include <__utility/swap.h>
18 
19 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
20 #pragma GCC system_header
21 #endif
22 
23 _LIBCPP_PUSH_MACROS
24 #include <__undef_macros>
25 
26 _LIBCPP_BEGIN_NAMESPACE_STD
27 
28 template <class _Compare, class _BidirectionalIterator>
29 _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
30 __next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
31 {
32     _BidirectionalIterator __i = __last;
33     if (__first == __last || __first == --__i)
34         return false;
35     while (true)
36     {
37         _BidirectionalIterator __ip1 = __i;
38         if (__comp(*--__i, *__ip1))
39         {
40             _BidirectionalIterator __j = __last;
41             while (!__comp(*__i, *--__j))
42                 ;
43             swap(*__i, *__j);
44             _VSTD::reverse(__ip1, __last);
45             return true;
46         }
47         if (__i == __first)
48         {
49             _VSTD::reverse(__first, __last);
50             return false;
51         }
52     }
53 }
54 
55 template <class _BidirectionalIterator, class _Compare>
56 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
57 bool
58 next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
59 {
60     typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
61     return _VSTD::__next_permutation<_Comp_ref>(__first, __last, __comp);
62 }
63 
64 template <class _BidirectionalIterator>
65 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
66 bool
67 next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
68 {
69     return _VSTD::next_permutation(__first, __last,
70                                   __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
71 }
72 
73 _LIBCPP_END_NAMESPACE_STD
74 
75 _LIBCPP_POP_MACROS
76 
77 #endif // _LIBCPP___ALGORITHM_NEXT_PERMUTATION_H
78