1// -*- C++ -*-
2//===-------------------------- algorithm ---------------------------------===//
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is dual licensed under the MIT and the University of Illinois Open
7// Source Licenses. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11#ifndef _LIBCPP_ALGORITHM
12#define _LIBCPP_ALGORITHM
13
14/*
15    algorithm synopsis
16
17#include <initializer_list>
18
19namespace std
20{
21
22template <class InputIterator, class Predicate>
23    bool
24    all_of(InputIterator first, InputIterator last, Predicate pred);
25
26template <class InputIterator, class Predicate>
27    bool
28    any_of(InputIterator first, InputIterator last, Predicate pred);
29
30template <class InputIterator, class Predicate>
31    bool
32    none_of(InputIterator first, InputIterator last, Predicate pred);
33
34template <class InputIterator, class Function>
35    Function
36    for_each(InputIterator first, InputIterator last, Function f);
37
38template <class InputIterator, class T>
39    InputIterator
40    find(InputIterator first, InputIterator last, const T& value);
41
42template <class InputIterator, class Predicate>
43    InputIterator
44    find_if(InputIterator first, InputIterator last, Predicate pred);
45
46template<class InputIterator, class Predicate>
47    InputIterator
48    find_if_not(InputIterator first, InputIterator last, Predicate pred);
49
50template <class ForwardIterator1, class ForwardIterator2>
51    ForwardIterator1
52    find_end(ForwardIterator1 first1, ForwardIterator1 last1,
53             ForwardIterator2 first2, ForwardIterator2 last2);
54
55template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
56    ForwardIterator1
57    find_end(ForwardIterator1 first1, ForwardIterator1 last1,
58             ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);
59
60template <class ForwardIterator1, class ForwardIterator2>
61    ForwardIterator1
62    find_first_of(ForwardIterator1 first1, ForwardIterator1 last1,
63                  ForwardIterator2 first2, ForwardIterator2 last2);
64
65template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
66    ForwardIterator1
67    find_first_of(ForwardIterator1 first1, ForwardIterator1 last1,
68                  ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);
69
70template <class ForwardIterator>
71    ForwardIterator
72    adjacent_find(ForwardIterator first, ForwardIterator last);
73
74template <class ForwardIterator, class BinaryPredicate>
75    ForwardIterator
76    adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
77
78template <class InputIterator, class T>
79    typename iterator_traits<InputIterator>::difference_type
80    count(InputIterator first, InputIterator last, const T& value);
81
82template <class InputIterator, class Predicate>
83    typename iterator_traits<InputIterator>::difference_type
84    count_if(InputIterator first, InputIterator last, Predicate pred);
85
86template <class InputIterator1, class InputIterator2>
87    pair<InputIterator1, InputIterator2>
88    mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);
89
90template <class InputIterator1, class InputIterator2>
91    pair<InputIterator1, InputIterator2>
92    mismatch(InputIterator1 first1, InputIterator1 last1,
93             InputIterator2 first2, InputIterator2 last2); // **C++14**
94
95template <class InputIterator1, class InputIterator2, class BinaryPredicate>
96    pair<InputIterator1, InputIterator2>
97    mismatch(InputIterator1 first1, InputIterator1 last1,
98             InputIterator2 first2, BinaryPredicate pred);
99
100template <class InputIterator1, class InputIterator2, class BinaryPredicate>
101    pair<InputIterator1, InputIterator2>
102    mismatch(InputIterator1 first1, InputIterator1 last1,
103             InputIterator2 first2, InputIterator2 last2,
104             BinaryPredicate pred); // **C++14**
105
106template <class InputIterator1, class InputIterator2>
107    bool
108    equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);
109
110template <class InputIterator1, class InputIterator2>
111    bool
112    equal(InputIterator1 first1, InputIterator1 last1,
113          InputIterator2 first2, InputIterator2 last2); // **C++14**
114
115template <class InputIterator1, class InputIterator2, class BinaryPredicate>
116    bool
117    equal(InputIterator1 first1, InputIterator1 last1,
118          InputIterator2 first2, BinaryPredicate pred);
119
120template <class InputIterator1, class InputIterator2, class BinaryPredicate>
121    bool
122    equal(InputIterator1 first1, InputIterator1 last1,
123          InputIterator2 first2, InputIterator2 last2,
124          BinaryPredicate pred); // **C++14**
125
126template<class ForwardIterator1, class ForwardIterator2>
127    bool
128    is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,
129                   ForwardIterator2 first2);
130
131template<class ForwardIterator1, class ForwardIterator2>
132    bool
133    is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,
134                   ForwardIterator2 first2, ForwardIterator2 last2); // **C++14**
135
136template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
137    bool
138    is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,
139                   ForwardIterator2 first2, BinaryPredicate pred);
140
141template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
142    bool
143    is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,
144                   ForwardIterator2 first2, ForwardIterator2 last2,
145                   BinaryPredicate pred);  // **C++14**
146
147template <class ForwardIterator1, class ForwardIterator2>
148    ForwardIterator1
149    search(ForwardIterator1 first1, ForwardIterator1 last1,
150           ForwardIterator2 first2, ForwardIterator2 last2);
151
152template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
153    ForwardIterator1
154    search(ForwardIterator1 first1, ForwardIterator1 last1,
155           ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);
156
157template <class ForwardIterator, class Size, class T>
158    ForwardIterator
159    search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value);
160
161template <class ForwardIterator, class Size, class T, class BinaryPredicate>
162    ForwardIterator
163    search_n(ForwardIterator first, ForwardIterator last,
164             Size count, const T& value, BinaryPredicate pred);
165
166template <class InputIterator, class OutputIterator>
167    OutputIterator
168    copy(InputIterator first, InputIterator last, OutputIterator result);
169
170template<class InputIterator, class OutputIterator, class Predicate>
171    OutputIterator
172    copy_if(InputIterator first, InputIterator last,
173            OutputIterator result, Predicate pred);
174
175template<class InputIterator, class Size, class OutputIterator>
176    OutputIterator
177    copy_n(InputIterator first, Size n, OutputIterator result);
178
179template <class BidirectionalIterator1, class BidirectionalIterator2>
180    BidirectionalIterator2
181    copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last,
182                  BidirectionalIterator2 result);
183
184template <class ForwardIterator1, class ForwardIterator2>
185    ForwardIterator2
186    swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);
187
188template <class ForwardIterator1, class ForwardIterator2>
189    void
190    iter_swap(ForwardIterator1 a, ForwardIterator2 b);
191
192template <class InputIterator, class OutputIterator, class UnaryOperation>
193    OutputIterator
194    transform(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op);
195
196template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation>
197    OutputIterator
198    transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
199              OutputIterator result, BinaryOperation binary_op);
200
201template <class ForwardIterator, class T>
202    void
203    replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value);
204
205template <class ForwardIterator, class Predicate, class T>
206    void
207    replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value);
208
209template <class InputIterator, class OutputIterator, class T>
210    OutputIterator
211    replace_copy(InputIterator first, InputIterator last, OutputIterator result,
212                 const T& old_value, const T& new_value);
213
214template <class InputIterator, class OutputIterator, class Predicate, class T>
215    OutputIterator
216    replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value);
217
218template <class ForwardIterator, class T>
219    void
220    fill(ForwardIterator first, ForwardIterator last, const T& value);
221
222template <class OutputIterator, class Size, class T>
223    OutputIterator
224    fill_n(OutputIterator first, Size n, const T& value);
225
226template <class ForwardIterator, class Generator>
227    void
228    generate(ForwardIterator first, ForwardIterator last, Generator gen);
229
230template <class OutputIterator, class Size, class Generator>
231    OutputIterator
232    generate_n(OutputIterator first, Size n, Generator gen);
233
234template <class ForwardIterator, class T>
235    ForwardIterator
236    remove(ForwardIterator first, ForwardIterator last, const T& value);
237
238template <class ForwardIterator, class Predicate>
239    ForwardIterator
240    remove_if(ForwardIterator first, ForwardIterator last, Predicate pred);
241
242template <class InputIterator, class OutputIterator, class T>
243    OutputIterator
244    remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value);
245
246template <class InputIterator, class OutputIterator, class Predicate>
247    OutputIterator
248    remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred);
249
250template <class ForwardIterator>
251    ForwardIterator
252    unique(ForwardIterator first, ForwardIterator last);
253
254template <class ForwardIterator, class BinaryPredicate>
255    ForwardIterator
256    unique(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
257
258template <class InputIterator, class OutputIterator>
259    OutputIterator
260    unique_copy(InputIterator first, InputIterator last, OutputIterator result);
261
262template <class InputIterator, class OutputIterator, class BinaryPredicate>
263    OutputIterator
264    unique_copy(InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate pred);
265
266template <class BidirectionalIterator>
267    void
268    reverse(BidirectionalIterator first, BidirectionalIterator last);
269
270template <class BidirectionalIterator, class OutputIterator>
271    OutputIterator
272    reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result);
273
274template <class ForwardIterator>
275    ForwardIterator
276    rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last);
277
278template <class ForwardIterator, class OutputIterator>
279    OutputIterator
280    rotate_copy(ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result);
281
282template <class RandomAccessIterator>
283    void
284    random_shuffle(RandomAccessIterator first, RandomAccessIterator last); // deprecated in C++14
285
286template <class RandomAccessIterator, class RandomNumberGenerator>
287    void
288    random_shuffle(RandomAccessIterator first, RandomAccessIterator last,
289                   RandomNumberGenerator& rand);  // deprecated in C++14
290
291template<class RandomAccessIterator, class UniformRandomNumberGenerator>
292    void shuffle(RandomAccessIterator first, RandomAccessIterator last,
293                 UniformRandomNumberGenerator&& g);
294
295template <class InputIterator, class Predicate>
296    bool
297    is_partitioned(InputIterator first, InputIterator last, Predicate pred);
298
299template <class ForwardIterator, class Predicate>
300    ForwardIterator
301    partition(ForwardIterator first, ForwardIterator last, Predicate pred);
302
303template <class InputIterator, class OutputIterator1,
304          class OutputIterator2, class Predicate>
305    pair<OutputIterator1, OutputIterator2>
306    partition_copy(InputIterator first, InputIterator last,
307                   OutputIterator1 out_true, OutputIterator2 out_false,
308                   Predicate pred);
309
310template <class ForwardIterator, class Predicate>
311    ForwardIterator
312    stable_partition(ForwardIterator first, ForwardIterator last, Predicate pred);
313
314template<class ForwardIterator, class Predicate>
315    ForwardIterator
316    partition_point(ForwardIterator first, ForwardIterator last, Predicate pred);
317
318template <class ForwardIterator>
319    bool
320    is_sorted(ForwardIterator first, ForwardIterator last);
321
322template <class ForwardIterator, class Compare>
323    bool
324    is_sorted(ForwardIterator first, ForwardIterator last, Compare comp);
325
326template<class ForwardIterator>
327    ForwardIterator
328    is_sorted_until(ForwardIterator first, ForwardIterator last);
329
330template <class ForwardIterator, class Compare>
331    ForwardIterator
332    is_sorted_until(ForwardIterator first, ForwardIterator last, Compare comp);
333
334template <class RandomAccessIterator>
335    void
336    sort(RandomAccessIterator first, RandomAccessIterator last);
337
338template <class RandomAccessIterator, class Compare>
339    void
340    sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
341
342template <class RandomAccessIterator>
343    void
344    stable_sort(RandomAccessIterator first, RandomAccessIterator last);
345
346template <class RandomAccessIterator, class Compare>
347    void
348    stable_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
349
350template <class RandomAccessIterator>
351    void
352    partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last);
353
354template <class RandomAccessIterator, class Compare>
355    void
356    partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp);
357
358template <class InputIterator, class RandomAccessIterator>
359    RandomAccessIterator
360    partial_sort_copy(InputIterator first, InputIterator last,
361                      RandomAccessIterator result_first, RandomAccessIterator result_last);
362
363template <class InputIterator, class RandomAccessIterator, class Compare>
364    RandomAccessIterator
365    partial_sort_copy(InputIterator first, InputIterator last,
366                      RandomAccessIterator result_first, RandomAccessIterator result_last, Compare comp);
367
368template <class RandomAccessIterator>
369    void
370    nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
371
372template <class RandomAccessIterator, class Compare>
373    void
374    nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp);
375
376template <class ForwardIterator, class T>
377    ForwardIterator
378    lower_bound(ForwardIterator first, ForwardIterator last, const T& value);
379
380template <class ForwardIterator, class T, class Compare>
381    ForwardIterator
382    lower_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);
383
384template <class ForwardIterator, class T>
385    ForwardIterator
386    upper_bound(ForwardIterator first, ForwardIterator last, const T& value);
387
388template <class ForwardIterator, class T, class Compare>
389    ForwardIterator
390    upper_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);
391
392template <class ForwardIterator, class T>
393    pair<ForwardIterator, ForwardIterator>
394    equal_range(ForwardIterator first, ForwardIterator last, const T& value);
395
396template <class ForwardIterator, class T, class Compare>
397    pair<ForwardIterator, ForwardIterator>
398    equal_range(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);
399
400template <class ForwardIterator, class T>
401    bool
402    binary_search(ForwardIterator first, ForwardIterator last, const T& value);
403
404template <class ForwardIterator, class T, class Compare>
405    bool
406    binary_search(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);
407
408template <class InputIterator1, class InputIterator2, class OutputIterator>
409    OutputIterator
410    merge(InputIterator1 first1, InputIterator1 last1,
411          InputIterator2 first2, InputIterator2 last2, OutputIterator result);
412
413template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
414    OutputIterator
415    merge(InputIterator1 first1, InputIterator1 last1,
416          InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
417
418template <class BidirectionalIterator>
419    void
420    inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last);
421
422template <class BidirectionalIterator, class Compare>
423    void
424    inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp);
425
426template <class InputIterator1, class InputIterator2>
427    bool
428    includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2);
429
430template <class InputIterator1, class InputIterator2, class Compare>
431    bool
432    includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp);
433
434template <class InputIterator1, class InputIterator2, class OutputIterator>
435    OutputIterator
436    set_union(InputIterator1 first1, InputIterator1 last1,
437              InputIterator2 first2, InputIterator2 last2, OutputIterator result);
438
439template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
440    OutputIterator
441    set_union(InputIterator1 first1, InputIterator1 last1,
442              InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
443
444template <class InputIterator1, class InputIterator2, class OutputIterator>
445    OutputIterator
446    set_intersection(InputIterator1 first1, InputIterator1 last1,
447                     InputIterator2 first2, InputIterator2 last2, OutputIterator result);
448
449template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
450    OutputIterator
451    set_intersection(InputIterator1 first1, InputIterator1 last1,
452                     InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
453
454template <class InputIterator1, class InputIterator2, class OutputIterator>
455    OutputIterator
456    set_difference(InputIterator1 first1, InputIterator1 last1,
457                   InputIterator2 first2, InputIterator2 last2, OutputIterator result);
458
459template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
460    OutputIterator
461    set_difference(InputIterator1 first1, InputIterator1 last1,
462                   InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
463
464template <class InputIterator1, class InputIterator2, class OutputIterator>
465    OutputIterator
466    set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,
467                             InputIterator2 first2, InputIterator2 last2, OutputIterator result);
468
469template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
470    OutputIterator
471    set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,
472                             InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
473
474template <class RandomAccessIterator>
475    void
476    push_heap(RandomAccessIterator first, RandomAccessIterator last);
477
478template <class RandomAccessIterator, class Compare>
479    void
480    push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
481
482template <class RandomAccessIterator>
483    void
484    pop_heap(RandomAccessIterator first, RandomAccessIterator last);
485
486template <class RandomAccessIterator, class Compare>
487    void
488    pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
489
490template <class RandomAccessIterator>
491    void
492    make_heap(RandomAccessIterator first, RandomAccessIterator last);
493
494template <class RandomAccessIterator, class Compare>
495    void
496    make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
497
498template <class RandomAccessIterator>
499    void
500    sort_heap(RandomAccessIterator first, RandomAccessIterator last);
501
502template <class RandomAccessIterator, class Compare>
503    void
504    sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
505
506template <class RandomAccessIterator>
507    bool
508    is_heap(RandomAccessIterator first, RandomAccessiterator last);
509
510template <class RandomAccessIterator, class Compare>
511    bool
512    is_heap(RandomAccessIterator first, RandomAccessiterator last, Compare comp);
513
514template <class RandomAccessIterator>
515    RandomAccessIterator
516    is_heap_until(RandomAccessIterator first, RandomAccessiterator last);
517
518template <class RandomAccessIterator, class Compare>
519    RandomAccessIterator
520    is_heap_until(RandomAccessIterator first, RandomAccessiterator last, Compare comp);
521
522template <class ForwardIterator>
523    ForwardIterator
524    min_element(ForwardIterator first, ForwardIterator last);  // constexpr in C++14
525
526template <class ForwardIterator, class Compare>
527    ForwardIterator
528    min_element(ForwardIterator first, ForwardIterator last, Compare comp);  // constexpr in C++14
529
530template <class T>
531    const T&
532    min(const T& a, const T& b);  // constexpr in C++14
533
534template <class T, class Compare>
535    const T&
536    min(const T& a, const T& b, Compare comp);  // constexpr in C++14
537
538template<class T>
539    T
540    min(initializer_list<T> t);  // constexpr in C++14
541
542template<class T, class Compare>
543    T
544    min(initializer_list<T> t, Compare comp);  // constexpr in C++14
545
546template <class ForwardIterator>
547    ForwardIterator
548    max_element(ForwardIterator first, ForwardIterator last);  // constexpr in C++14
549
550template <class ForwardIterator, class Compare>
551    ForwardIterator
552    max_element(ForwardIterator first, ForwardIterator last, Compare comp);  // constexpr in C++14
553
554template <class T>
555    const T&
556    max(const T& a, const T& b); // constexpr in C++14
557
558template <class T, class Compare>
559    const T&
560    max(const T& a, const T& b, Compare comp);  // constexpr in C++14
561
562template<class T>
563    T
564    max(initializer_list<T> t);  // constexpr in C++14
565
566template<class T, class Compare>
567    T
568    max(initializer_list<T> t, Compare comp);  // constexpr in C++14
569
570template<class ForwardIterator>
571    pair<ForwardIterator, ForwardIterator>
572    minmax_element(ForwardIterator first, ForwardIterator last);   // constexpr in C++14
573
574template<class ForwardIterator, class Compare>
575    pair<ForwardIterator, ForwardIterator>
576    minmax_element(ForwardIterator first, ForwardIterator last, Compare comp);   // constexpr in C++14
577
578template<class T>
579    pair<const T&, const T&>
580    minmax(const T& a, const T& b);  // constexpr in C++14
581
582template<class T, class Compare>
583    pair<const T&, const T&>
584    minmax(const T& a, const T& b, Compare comp);  // constexpr in C++14
585
586template<class T>
587    pair<T, T>
588    minmax(initializer_list<T> t);  // constexpr in C++14
589
590template<class T, class Compare>
591    pair<T, T>
592    minmax(initializer_list<T> t, Compare comp);  // constexpr in C++14
593
594template <class InputIterator1, class InputIterator2>
595    bool
596    lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2);
597
598template <class InputIterator1, class InputIterator2, class Compare>
599    bool
600    lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
601                            InputIterator2 first2, InputIterator2 last2, Compare comp);
602
603template <class BidirectionalIterator>
604    bool
605    next_permutation(BidirectionalIterator first, BidirectionalIterator last);
606
607template <class BidirectionalIterator, class Compare>
608    bool
609    next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp);
610
611template <class BidirectionalIterator>
612    bool
613    prev_permutation(BidirectionalIterator first, BidirectionalIterator last);
614
615template <class BidirectionalIterator, class Compare>
616    bool
617    prev_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp);
618
619}  // std
620
621*/
622
623#include <__config>
624#include <initializer_list>
625#include <type_traits>
626#include <cstring>
627#include <utility>
628#include <memory>
629#include <iterator>
630#include <cstddef>
631
632#if defined(__IBMCPP__)
633#include "support/ibm/support.h"
634#endif
635#if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__)
636#include "support/win32/support.h"
637#endif
638
639#include <__undef_min_max>
640
641#include <__debug>
642
643#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
644#pragma GCC system_header
645#endif
646
647_LIBCPP_BEGIN_NAMESPACE_STD
648
649// I'd like to replace these with _VSTD::equal_to<void>, but can't because:
650//   * That only works with C++14 and later, and
651//   * We haven't included <functional> here.
652template <class _T1, class _T2 = _T1>
653struct __equal_to
654{
655    _LIBCPP_INLINE_VISIBILITY bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
656    _LIBCPP_INLINE_VISIBILITY bool operator()(const _T1& __x, const _T2& __y) const {return __x == __y;}
657    _LIBCPP_INLINE_VISIBILITY bool operator()(const _T2& __x, const _T1& __y) const {return __x == __y;}
658    _LIBCPP_INLINE_VISIBILITY bool operator()(const _T2& __x, const _T2& __y) const {return __x == __y;}
659};
660
661template <class _T1>
662struct __equal_to<_T1, _T1>
663{
664    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
665    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
666};
667
668template <class _T1>
669struct __equal_to<const _T1, _T1>
670{
671    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
672    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
673};
674
675template <class _T1>
676struct __equal_to<_T1, const _T1>
677{
678    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
679    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
680};
681
682template <class _T1, class _T2 = _T1>
683struct __less
684{
685    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
686    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
687
688    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
689    bool operator()(const _T1& __x, const _T2& __y) const {return __x < __y;}
690
691    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
692    bool operator()(const _T2& __x, const _T1& __y) const {return __x < __y;}
693
694    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
695    bool operator()(const _T2& __x, const _T2& __y) const {return __x < __y;}
696};
697
698template <class _T1>
699struct __less<_T1, _T1>
700{
701    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
702    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
703};
704
705template <class _T1>
706struct __less<const _T1, _T1>
707{
708    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
709    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
710};
711
712template <class _T1>
713struct __less<_T1, const _T1>
714{
715    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
716    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
717};
718
719template <class _Predicate>
720class __negate
721{
722private:
723    _Predicate __p_;
724public:
725    _LIBCPP_INLINE_VISIBILITY __negate() {}
726
727    _LIBCPP_INLINE_VISIBILITY
728    explicit __negate(_Predicate __p) : __p_(__p) {}
729
730    template <class _T1>
731    _LIBCPP_INLINE_VISIBILITY
732    bool operator()(const _T1& __x) {return !__p_(__x);}
733
734    template <class _T1, class _T2>
735    _LIBCPP_INLINE_VISIBILITY
736    bool operator()(const _T1& __x, const _T2& __y) {return !__p_(__x, __y);}
737};
738
739#ifdef _LIBCPP_DEBUG
740
741template <class _Compare>
742struct __debug_less
743{
744    _Compare __comp_;
745    __debug_less(_Compare& __c) : __comp_(__c) {}
746    template <class _Tp, class _Up>
747    bool operator()(const _Tp& __x, const _Up& __y)
748    {
749        bool __r = __comp_(__x, __y);
750        if (__r)
751            _LIBCPP_ASSERT(!__comp_(__y, __x), "Comparator does not induce a strict weak ordering");
752        return __r;
753    }
754};
755
756#endif  // _LIBCPP_DEBUG
757
758// Precondition:  __x != 0
759inline _LIBCPP_INLINE_VISIBILITY
760unsigned
761__ctz(unsigned __x)
762{
763    return static_cast<unsigned>(__builtin_ctz(__x));
764}
765
766inline _LIBCPP_INLINE_VISIBILITY
767unsigned long
768__ctz(unsigned long __x)
769{
770    return static_cast<unsigned long>(__builtin_ctzl(__x));
771}
772
773inline _LIBCPP_INLINE_VISIBILITY
774unsigned long long
775__ctz(unsigned long long __x)
776{
777    return static_cast<unsigned long long>(__builtin_ctzll(__x));
778}
779
780// Precondition:  __x != 0
781inline _LIBCPP_INLINE_VISIBILITY
782unsigned
783__clz(unsigned __x)
784{
785    return static_cast<unsigned>(__builtin_clz(__x));
786}
787
788inline _LIBCPP_INLINE_VISIBILITY
789unsigned long
790__clz(unsigned long __x)
791{
792    return static_cast<unsigned long>(__builtin_clzl (__x));
793}
794
795inline _LIBCPP_INLINE_VISIBILITY
796unsigned long long
797__clz(unsigned long long __x)
798{
799    return static_cast<unsigned long long>(__builtin_clzll(__x));
800}
801
802inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned           __x) {return __builtin_popcount  (__x);}
803inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned      long __x) {return __builtin_popcountl (__x);}
804inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned long long __x) {return __builtin_popcountll(__x);}
805
806// all_of
807
808template <class _InputIterator, class _Predicate>
809inline _LIBCPP_INLINE_VISIBILITY
810bool
811all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
812{
813    for (; __first != __last; ++__first)
814        if (!__pred(*__first))
815            return false;
816    return true;
817}
818
819// any_of
820
821template <class _InputIterator, class _Predicate>
822inline _LIBCPP_INLINE_VISIBILITY
823bool
824any_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
825{
826    for (; __first != __last; ++__first)
827        if (__pred(*__first))
828            return true;
829    return false;
830}
831
832// none_of
833
834template <class _InputIterator, class _Predicate>
835inline _LIBCPP_INLINE_VISIBILITY
836bool
837none_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
838{
839    for (; __first != __last; ++__first)
840        if (__pred(*__first))
841            return false;
842    return true;
843}
844
845// for_each
846
847template <class _InputIterator, class _Function>
848inline _LIBCPP_INLINE_VISIBILITY
849_Function
850for_each(_InputIterator __first, _InputIterator __last, _Function __f)
851{
852    for (; __first != __last; ++__first)
853        __f(*__first);
854    return _VSTD::move(__f);  // explicitly moved for (emulated) C++03
855}
856
857// find
858
859template <class _InputIterator, class _Tp>
860inline _LIBCPP_INLINE_VISIBILITY
861_InputIterator
862find(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
863{
864    for (; __first != __last; ++__first)
865        if (*__first == __value_)
866            break;
867    return __first;
868}
869
870// find_if
871
872template <class _InputIterator, class _Predicate>
873inline _LIBCPP_INLINE_VISIBILITY
874_InputIterator
875find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
876{
877    for (; __first != __last; ++__first)
878        if (__pred(*__first))
879            break;
880    return __first;
881}
882
883// find_if_not
884
885template<class _InputIterator, class _Predicate>
886inline _LIBCPP_INLINE_VISIBILITY
887_InputIterator
888find_if_not(_InputIterator __first, _InputIterator __last, _Predicate __pred)
889{
890    for (; __first != __last; ++__first)
891        if (!__pred(*__first))
892            break;
893    return __first;
894}
895
896// find_end
897
898template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
899_ForwardIterator1
900__find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
901           _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred,
902           forward_iterator_tag, forward_iterator_tag)
903{
904    // modeled after search algorithm
905    _ForwardIterator1 __r = __last1;  // __last1 is the "default" answer
906    if (__first2 == __last2)
907        return __r;
908    while (true)
909    {
910        while (true)
911        {
912            if (__first1 == __last1)         // if source exhausted return last correct answer
913                return __r;                  //    (or __last1 if never found)
914            if (__pred(*__first1, *__first2))
915                break;
916            ++__first1;
917        }
918        // *__first1 matches *__first2, now match elements after here
919        _ForwardIterator1 __m1 = __first1;
920        _ForwardIterator2 __m2 = __first2;
921        while (true)
922        {
923            if (++__m2 == __last2)
924            {                         // Pattern exhaused, record answer and search for another one
925                __r = __first1;
926                ++__first1;
927                break;
928            }
929            if (++__m1 == __last1)     // Source exhausted, return last answer
930                return __r;
931            if (!__pred(*__m1, *__m2))  // mismatch, restart with a new __first
932            {
933                ++__first1;
934                break;
935            }  // else there is a match, check next elements
936        }
937    }
938}
939
940template <class _BinaryPredicate, class _BidirectionalIterator1, class _BidirectionalIterator2>
941_BidirectionalIterator1
942__find_end(_BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1,
943           _BidirectionalIterator2 __first2, _BidirectionalIterator2 __last2, _BinaryPredicate __pred,
944           bidirectional_iterator_tag, bidirectional_iterator_tag)
945{
946    // modeled after search algorithm (in reverse)
947    if (__first2 == __last2)
948        return __last1;  // Everything matches an empty sequence
949    _BidirectionalIterator1 __l1 = __last1;
950    _BidirectionalIterator2 __l2 = __last2;
951    --__l2;
952    while (true)
953    {
954        // Find last element in sequence 1 that matchs *(__last2-1), with a mininum of loop checks
955        while (true)
956        {
957            if (__first1 == __l1)  // return __last1 if no element matches *__first2
958                return __last1;
959            if (__pred(*--__l1, *__l2))
960                break;
961        }
962        // *__l1 matches *__l2, now match elements before here
963        _BidirectionalIterator1 __m1 = __l1;
964        _BidirectionalIterator2 __m2 = __l2;
965        while (true)
966        {
967            if (__m2 == __first2)  // If pattern exhausted, __m1 is the answer (works for 1 element pattern)
968                return __m1;
969            if (__m1 == __first1)  // Otherwise if source exhaused, pattern not found
970                return __last1;
971            if (!__pred(*--__m1, *--__m2))  // if there is a mismatch, restart with a new __l1
972            {
973                break;
974            }  // else there is a match, check next elements
975        }
976    }
977}
978
979template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
980_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1
981__find_end(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
982           _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
983           random_access_iterator_tag, random_access_iterator_tag)
984{
985    // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
986    typename iterator_traits<_RandomAccessIterator2>::difference_type __len2 = __last2 - __first2;
987    if (__len2 == 0)
988        return __last1;
989    typename iterator_traits<_RandomAccessIterator1>::difference_type __len1 = __last1 - __first1;
990    if (__len1 < __len2)
991        return __last1;
992    const _RandomAccessIterator1 __s = __first1 + (__len2 - 1);  // End of pattern match can't go before here
993    _RandomAccessIterator1 __l1 = __last1;
994    _RandomAccessIterator2 __l2 = __last2;
995    --__l2;
996    while (true)
997    {
998        while (true)
999        {
1000            if (__s == __l1)
1001                return __last1;
1002            if (__pred(*--__l1, *__l2))
1003                break;
1004        }
1005        _RandomAccessIterator1 __m1 = __l1;
1006        _RandomAccessIterator2 __m2 = __l2;
1007        while (true)
1008        {
1009            if (__m2 == __first2)
1010                return __m1;
1011                                 // no need to check range on __m1 because __s guarantees we have enough source
1012            if (!__pred(*--__m1, *--__m2))
1013            {
1014                break;
1015            }
1016        }
1017    }
1018}
1019
1020template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1021inline _LIBCPP_INLINE_VISIBILITY
1022_ForwardIterator1
1023find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1024         _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
1025{
1026    return _VSTD::__find_end<typename add_lvalue_reference<_BinaryPredicate>::type>
1027                         (__first1, __last1, __first2, __last2, __pred,
1028                          typename iterator_traits<_ForwardIterator1>::iterator_category(),
1029                          typename iterator_traits<_ForwardIterator2>::iterator_category());
1030}
1031
1032template <class _ForwardIterator1, class _ForwardIterator2>
1033inline _LIBCPP_INLINE_VISIBILITY
1034_ForwardIterator1
1035find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1036         _ForwardIterator2 __first2, _ForwardIterator2 __last2)
1037{
1038    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
1039    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
1040    return _VSTD::find_end(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
1041}
1042
1043// find_first_of
1044
1045template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1046_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator1
1047__find_first_of_ce(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1048              _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
1049{
1050    for (; __first1 != __last1; ++__first1)
1051        for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
1052            if (__pred(*__first1, *__j))
1053                return __first1;
1054    return __last1;
1055}
1056
1057
1058template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1059inline _LIBCPP_INLINE_VISIBILITY
1060_ForwardIterator1
1061find_first_of(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1062              _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
1063{
1064    return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __pred);
1065}
1066
1067template <class _ForwardIterator1, class _ForwardIterator2>
1068inline _LIBCPP_INLINE_VISIBILITY
1069_ForwardIterator1
1070find_first_of(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1071              _ForwardIterator2 __first2, _ForwardIterator2 __last2)
1072{
1073    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
1074    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
1075    return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
1076}
1077
1078// adjacent_find
1079
1080template <class _ForwardIterator, class _BinaryPredicate>
1081inline _LIBCPP_INLINE_VISIBILITY
1082_ForwardIterator
1083adjacent_find(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
1084{
1085    if (__first != __last)
1086    {
1087        _ForwardIterator __i = __first;
1088        while (++__i != __last)
1089        {
1090            if (__pred(*__first, *__i))
1091                return __first;
1092            __first = __i;
1093        }
1094    }
1095    return __last;
1096}
1097
1098template <class _ForwardIterator>
1099inline _LIBCPP_INLINE_VISIBILITY
1100_ForwardIterator
1101adjacent_find(_ForwardIterator __first, _ForwardIterator __last)
1102{
1103    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
1104    return _VSTD::adjacent_find(__first, __last, __equal_to<__v>());
1105}
1106
1107// count
1108
1109template <class _InputIterator, class _Tp>
1110inline _LIBCPP_INLINE_VISIBILITY
1111typename iterator_traits<_InputIterator>::difference_type
1112count(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
1113{
1114    typename iterator_traits<_InputIterator>::difference_type __r(0);
1115    for (; __first != __last; ++__first)
1116        if (*__first == __value_)
1117            ++__r;
1118    return __r;
1119}
1120
1121// count_if
1122
1123template <class _InputIterator, class _Predicate>
1124inline _LIBCPP_INLINE_VISIBILITY
1125typename iterator_traits<_InputIterator>::difference_type
1126count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
1127{
1128    typename iterator_traits<_InputIterator>::difference_type __r(0);
1129    for (; __first != __last; ++__first)
1130        if (__pred(*__first))
1131            ++__r;
1132    return __r;
1133}
1134
1135// mismatch
1136
1137template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
1138inline _LIBCPP_INLINE_VISIBILITY
1139pair<_InputIterator1, _InputIterator2>
1140mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
1141         _InputIterator2 __first2, _BinaryPredicate __pred)
1142{
1143    for (; __first1 != __last1; ++__first1, (void) ++__first2)
1144        if (!__pred(*__first1, *__first2))
1145            break;
1146    return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
1147}
1148
1149template <class _InputIterator1, class _InputIterator2>
1150inline _LIBCPP_INLINE_VISIBILITY
1151pair<_InputIterator1, _InputIterator2>
1152mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
1153{
1154    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
1155    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
1156    return _VSTD::mismatch(__first1, __last1, __first2, __equal_to<__v1, __v2>());
1157}
1158
1159#if _LIBCPP_STD_VER > 11
1160template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
1161inline _LIBCPP_INLINE_VISIBILITY
1162pair<_InputIterator1, _InputIterator2>
1163mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
1164         _InputIterator2 __first2, _InputIterator2 __last2,
1165         _BinaryPredicate __pred)
1166{
1167    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
1168        if (!__pred(*__first1, *__first2))
1169            break;
1170    return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
1171}
1172
1173template <class _InputIterator1, class _InputIterator2>
1174inline _LIBCPP_INLINE_VISIBILITY
1175pair<_InputIterator1, _InputIterator2>
1176mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
1177         _InputIterator2 __first2, _InputIterator2 __last2)
1178{
1179    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
1180    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
1181    return _VSTD::mismatch(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
1182}
1183#endif
1184
1185// equal
1186
1187template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
1188inline _LIBCPP_INLINE_VISIBILITY
1189bool
1190equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __pred)
1191{
1192    for (; __first1 != __last1; ++__first1, (void) ++__first2)
1193        if (!__pred(*__first1, *__first2))
1194            return false;
1195    return true;
1196}
1197
1198template <class _InputIterator1, class _InputIterator2>
1199inline _LIBCPP_INLINE_VISIBILITY
1200bool
1201equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
1202{
1203    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
1204    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
1205    return _VSTD::equal(__first1, __last1, __first2, __equal_to<__v1, __v2>());
1206}
1207
1208#if _LIBCPP_STD_VER > 11
1209template <class _BinaryPredicate, class _InputIterator1, class _InputIterator2>
1210inline _LIBCPP_INLINE_VISIBILITY
1211bool
1212__equal(_InputIterator1 __first1, _InputIterator1 __last1,
1213        _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __pred,
1214        input_iterator_tag, input_iterator_tag )
1215{
1216    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
1217        if (!__pred(*__first1, *__first2))
1218            return false;
1219    return __first1 == __last1 && __first2 == __last2;
1220}
1221
1222template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
1223inline _LIBCPP_INLINE_VISIBILITY
1224bool
1225__equal(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
1226        _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
1227      random_access_iterator_tag, random_access_iterator_tag )
1228{
1229    if ( _VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
1230        return false;
1231    return _VSTD::equal<_RandomAccessIterator1, _RandomAccessIterator2,
1232                        typename add_lvalue_reference<_BinaryPredicate>::type>
1233                       (__first1, __last1, __first2, __pred );
1234}
1235
1236template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
1237inline _LIBCPP_INLINE_VISIBILITY
1238bool
1239equal(_InputIterator1 __first1, _InputIterator1 __last1,
1240      _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __pred )
1241{
1242    return _VSTD::__equal<typename add_lvalue_reference<_BinaryPredicate>::type>
1243       (__first1, __last1, __first2, __last2, __pred,
1244        typename iterator_traits<_InputIterator1>::iterator_category(),
1245        typename iterator_traits<_InputIterator2>::iterator_category());
1246}
1247
1248template <class _InputIterator1, class _InputIterator2>
1249inline _LIBCPP_INLINE_VISIBILITY
1250bool
1251equal(_InputIterator1 __first1, _InputIterator1 __last1,
1252      _InputIterator2 __first2, _InputIterator2 __last2)
1253{
1254    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
1255    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
1256    return _VSTD::__equal(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>(),
1257        typename iterator_traits<_InputIterator1>::iterator_category(),
1258        typename iterator_traits<_InputIterator2>::iterator_category());
1259}
1260#endif
1261
1262// is_permutation
1263
1264template<class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1265bool
1266is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1267               _ForwardIterator2 __first2, _BinaryPredicate __pred)
1268{
1269    // shorten sequences as much as possible by lopping of any equal parts
1270    for (; __first1 != __last1; ++__first1, (void) ++__first2)
1271        if (!__pred(*__first1, *__first2))
1272            goto __not_done;
1273    return true;
1274__not_done:
1275    // __first1 != __last1 && *__first1 != *__first2
1276    typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
1277    _D1 __l1 = _VSTD::distance(__first1, __last1);
1278    if (__l1 == _D1(1))
1279        return false;
1280    _ForwardIterator2 __last2 = _VSTD::next(__first2, __l1);
1281    // For each element in [f1, l1) see if there are the same number of
1282    //    equal elements in [f2, l2)
1283    for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
1284    {
1285        // Have we already counted the number of *__i in [f1, l1)?
1286        for (_ForwardIterator1 __j = __first1; __j != __i; ++__j)
1287            if (__pred(*__j, *__i))
1288                goto __next_iter;
1289        {
1290            // Count number of *__i in [f2, l2)
1291            _D1 __c2 = 0;
1292            for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
1293                if (__pred(*__i, *__j))
1294                    ++__c2;
1295            if (__c2 == 0)
1296                return false;
1297            // Count number of *__i in [__i, l1) (we can start with 1)
1298            _D1 __c1 = 1;
1299            for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
1300                if (__pred(*__i, *__j))
1301                    ++__c1;
1302            if (__c1 != __c2)
1303                return false;
1304        }
1305__next_iter:;
1306    }
1307    return true;
1308}
1309
1310template<class _ForwardIterator1, class _ForwardIterator2>
1311inline _LIBCPP_INLINE_VISIBILITY
1312bool
1313is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1314               _ForwardIterator2 __first2)
1315{
1316    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
1317    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
1318    return _VSTD::is_permutation(__first1, __last1, __first2, __equal_to<__v1, __v2>());
1319}
1320
1321#if _LIBCPP_STD_VER > 11
1322template<class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
1323bool
1324__is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1325                 _ForwardIterator2 __first2, _ForwardIterator2 __last2,
1326                 _BinaryPredicate __pred,
1327                 forward_iterator_tag, forward_iterator_tag )
1328{
1329    // shorten sequences as much as possible by lopping of any equal parts
1330    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
1331        if (!__pred(*__first1, *__first2))
1332            goto __not_done;
1333    return __first1 == __last1 && __first2 == __last2;
1334__not_done:
1335    // __first1 != __last1 && __first2 != __last2 && *__first1 != *__first2
1336    typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
1337    _D1 __l1 = _VSTD::distance(__first1, __last1);
1338
1339    typedef typename iterator_traits<_ForwardIterator2>::difference_type _D2;
1340    _D2 __l2 = _VSTD::distance(__first2, __last2);
1341    if (__l1 != __l2)
1342        return false;
1343
1344    // For each element in [f1, l1) see if there are the same number of
1345    //    equal elements in [f2, l2)
1346    for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
1347    {
1348        // Have we already counted the number of *__i in [f1, l1)?
1349        for (_ForwardIterator1 __j = __first1; __j != __i; ++__j)
1350            if (__pred(*__j, *__i))
1351                goto __next_iter;
1352        {
1353            // Count number of *__i in [f2, l2)
1354            _D1 __c2 = 0;
1355            for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
1356                if (__pred(*__i, *__j))
1357                    ++__c2;
1358            if (__c2 == 0)
1359                return false;
1360            // Count number of *__i in [__i, l1) (we can start with 1)
1361            _D1 __c1 = 1;
1362            for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
1363                if (__pred(*__i, *__j))
1364                    ++__c1;
1365            if (__c1 != __c2)
1366                return false;
1367        }
1368__next_iter:;
1369    }
1370    return true;
1371}
1372
1373template<class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
1374bool
1375__is_permutation(_RandomAccessIterator1 __first1, _RandomAccessIterator2 __last1,
1376               _RandomAccessIterator1 __first2, _RandomAccessIterator2 __last2,
1377               _BinaryPredicate __pred,
1378               random_access_iterator_tag, random_access_iterator_tag )
1379{
1380    if ( _VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
1381        return false;
1382    return _VSTD::is_permutation<_RandomAccessIterator1, _RandomAccessIterator2,
1383                                 typename add_lvalue_reference<_BinaryPredicate>::type>
1384                                (__first1, __last1, __first2, __pred );
1385}
1386
1387template<class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1388inline _LIBCPP_INLINE_VISIBILITY
1389bool
1390is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1391               _ForwardIterator2 __first2, _ForwardIterator2 __last2,
1392               _BinaryPredicate __pred )
1393{
1394    return _VSTD::__is_permutation<typename add_lvalue_reference<_BinaryPredicate>::type>
1395       (__first1, __last1, __first2, __last2, __pred,
1396        typename iterator_traits<_ForwardIterator1>::iterator_category(),
1397        typename iterator_traits<_ForwardIterator2>::iterator_category());
1398}
1399
1400template<class _ForwardIterator1, class _ForwardIterator2>
1401inline _LIBCPP_INLINE_VISIBILITY
1402bool
1403is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1404               _ForwardIterator2 __first2, _ForwardIterator2 __last2)
1405{
1406    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
1407    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
1408    return _VSTD::__is_permutation(__first1, __last1, __first2, __last2,
1409        __equal_to<__v1, __v2>(),
1410        typename iterator_traits<_ForwardIterator1>::iterator_category(),
1411        typename iterator_traits<_ForwardIterator2>::iterator_category());
1412}
1413#endif
1414
1415// search
1416
1417template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
1418_ForwardIterator1
1419__search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1420         _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred,
1421         forward_iterator_tag, forward_iterator_tag)
1422{
1423    if (__first2 == __last2)
1424        return __first1;  // Everything matches an empty sequence
1425    while (true)
1426    {
1427        // Find first element in sequence 1 that matchs *__first2, with a mininum of loop checks
1428        while (true)
1429        {
1430            if (__first1 == __last1)  // return __last1 if no element matches *__first2
1431                return __last1;
1432            if (__pred(*__first1, *__first2))
1433                break;
1434            ++__first1;
1435        }
1436        // *__first1 matches *__first2, now match elements after here
1437        _ForwardIterator1 __m1 = __first1;
1438        _ForwardIterator2 __m2 = __first2;
1439        while (true)
1440        {
1441            if (++__m2 == __last2)  // If pattern exhausted, __first1 is the answer (works for 1 element pattern)
1442                return __first1;
1443            if (++__m1 == __last1)  // Otherwise if source exhaused, pattern not found
1444                return __last1;
1445            if (!__pred(*__m1, *__m2))  // if there is a mismatch, restart with a new __first1
1446            {
1447                ++__first1;
1448                break;
1449            }  // else there is a match, check next elements
1450        }
1451    }
1452}
1453
1454template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
1455_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1
1456__search(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
1457           _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
1458           random_access_iterator_tag, random_access_iterator_tag)
1459{
1460    typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _D1;
1461    typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _D2;
1462    // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
1463    _D2 __len2 = __last2 - __first2;
1464    if (__len2 == 0)
1465        return __first1;
1466    _D1 __len1 = __last1 - __first1;
1467    if (__len1 < __len2)
1468        return __last1;
1469    const _RandomAccessIterator1 __s = __last1 - (__len2 - 1);  // Start of pattern match can't go beyond here
1470    while (true)
1471    {
1472#if !_LIBCPP_UNROLL_LOOPS
1473        while (true)
1474        {
1475            if (__first1 == __s)
1476                return __last1;
1477            if (__pred(*__first1, *__first2))
1478                break;
1479            ++__first1;
1480        }
1481#else  // !_LIBCPP_UNROLL_LOOPS
1482        for (_D1 __loop_unroll = (__s - __first1) / 4; __loop_unroll > 0; --__loop_unroll)
1483        {
1484            if (__pred(*__first1, *__first2))
1485                goto __phase2;
1486            if (__pred(*++__first1, *__first2))
1487                goto __phase2;
1488            if (__pred(*++__first1, *__first2))
1489                goto __phase2;
1490            if (__pred(*++__first1, *__first2))
1491                goto __phase2;
1492            ++__first1;
1493        }
1494        switch (__s - __first1)
1495        {
1496        case 3:
1497            if (__pred(*__first1, *__first2))
1498                break;
1499            ++__first1;
1500        case 2:
1501            if (__pred(*__first1, *__first2))
1502                break;
1503            ++__first1;
1504        case 1:
1505            if (__pred(*__first1, *__first2))
1506                break;
1507        case 0:
1508            return __last1;
1509        }
1510    __phase2:
1511#endif  // !_LIBCPP_UNROLL_LOOPS
1512        _RandomAccessIterator1 __m1 = __first1;
1513        _RandomAccessIterator2 __m2 = __first2;
1514#if !_LIBCPP_UNROLL_LOOPS
1515         while (true)
1516         {
1517             if (++__m2 == __last2)
1518                 return __first1;
1519             ++__m1;          // no need to check range on __m1 because __s guarantees we have enough source
1520             if (!__pred(*__m1, *__m2))
1521             {
1522                 ++__first1;
1523                 break;
1524             }
1525         }
1526#else  // !_LIBCPP_UNROLL_LOOPS
1527        ++__m2;
1528        ++__m1;
1529        for (_D2 __loop_unroll = (__last2 - __m2) / 4; __loop_unroll > 0; --__loop_unroll)
1530        {
1531            if (!__pred(*__m1, *__m2))
1532                goto __continue;
1533            if (!__pred(*++__m1, *++__m2))
1534                goto __continue;
1535            if (!__pred(*++__m1, *++__m2))
1536                goto __continue;
1537            if (!__pred(*++__m1, *++__m2))
1538                goto __continue;
1539            ++__m1;
1540            ++__m2;
1541        }
1542        switch (__last2 - __m2)
1543        {
1544        case 3:
1545            if (!__pred(*__m1, *__m2))
1546                break;
1547            ++__m1;
1548            ++__m2;
1549        case 2:
1550            if (!__pred(*__m1, *__m2))
1551                break;
1552            ++__m1;
1553            ++__m2;
1554        case 1:
1555            if (!__pred(*__m1, *__m2))
1556                break;
1557        case 0:
1558            return __first1;
1559        }
1560    __continue:
1561        ++__first1;
1562#endif  // !_LIBCPP_UNROLL_LOOPS
1563    }
1564}
1565
1566template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
1567inline _LIBCPP_INLINE_VISIBILITY
1568_ForwardIterator1
1569search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1570       _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
1571{
1572    return _VSTD::__search<typename add_lvalue_reference<_BinaryPredicate>::type>
1573                         (__first1, __last1, __first2, __last2, __pred,
1574                          typename std::iterator_traits<_ForwardIterator1>::iterator_category(),
1575                          typename std::iterator_traits<_ForwardIterator2>::iterator_category());
1576}
1577
1578template <class _ForwardIterator1, class _ForwardIterator2>
1579inline _LIBCPP_INLINE_VISIBILITY
1580_ForwardIterator1
1581search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
1582       _ForwardIterator2 __first2, _ForwardIterator2 __last2)
1583{
1584    typedef typename std::iterator_traits<_ForwardIterator1>::value_type __v1;
1585    typedef typename std::iterator_traits<_ForwardIterator2>::value_type __v2;
1586    return _VSTD::search(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
1587}
1588
1589// search_n
1590
1591template <class _BinaryPredicate, class _ForwardIterator, class _Size, class _Tp>
1592_ForwardIterator
1593__search_n(_ForwardIterator __first, _ForwardIterator __last,
1594           _Size __count, const _Tp& __value_, _BinaryPredicate __pred, forward_iterator_tag)
1595{
1596    if (__count <= 0)
1597        return __first;
1598    while (true)
1599    {
1600        // Find first element in sequence that matchs __value_, with a mininum of loop checks
1601        while (true)
1602        {
1603            if (__first == __last)  // return __last if no element matches __value_
1604                return __last;
1605            if (__pred(*__first, __value_))
1606                break;
1607            ++__first;
1608        }
1609        // *__first matches __value_, now match elements after here
1610        _ForwardIterator __m = __first;
1611        _Size __c(0);
1612        while (true)
1613        {
1614            if (++__c == __count)  // If pattern exhausted, __first is the answer (works for 1 element pattern)
1615                return __first;
1616            if (++__m == __last)  // Otherwise if source exhaused, pattern not found
1617                return __last;
1618            if (!__pred(*__m, __value_))  // if there is a mismatch, restart with a new __first
1619            {
1620                __first = __m;
1621                ++__first;
1622                break;
1623            }  // else there is a match, check next elements
1624        }
1625    }
1626}
1627
1628template <class _BinaryPredicate, class _RandomAccessIterator, class _Size, class _Tp>
1629_RandomAccessIterator
1630__search_n(_RandomAccessIterator __first, _RandomAccessIterator __last,
1631           _Size __count, const _Tp& __value_, _BinaryPredicate __pred, random_access_iterator_tag)
1632{
1633    if (__count <= 0)
1634        return __first;
1635    _Size __len = static_cast<_Size>(__last - __first);
1636    if (__len < __count)
1637        return __last;
1638    const _RandomAccessIterator __s = __last - (__count - 1);  // Start of pattern match can't go beyond here
1639    while (true)
1640    {
1641        // Find first element in sequence that matchs __value_, with a mininum of loop checks
1642        while (true)
1643        {
1644            if (__first >= __s)  // return __last if no element matches __value_
1645                return __last;
1646            if (__pred(*__first, __value_))
1647                break;
1648            ++__first;
1649        }
1650        // *__first matches __value_, now match elements after here
1651        _RandomAccessIterator __m = __first;
1652        _Size __c(0);
1653        while (true)
1654        {
1655            if (++__c == __count)  // If pattern exhausted, __first is the answer (works for 1 element pattern)
1656                return __first;
1657             ++__m;          // no need to check range on __m because __s guarantees we have enough source
1658            if (!__pred(*__m, __value_))  // if there is a mismatch, restart with a new __first
1659            {
1660                __first = __m;
1661                ++__first;
1662                break;
1663            }  // else there is a match, check next elements
1664        }
1665    }
1666}
1667
1668template <class _ForwardIterator, class _Size, class _Tp, class _BinaryPredicate>
1669inline _LIBCPP_INLINE_VISIBILITY
1670_ForwardIterator
1671search_n(_ForwardIterator __first, _ForwardIterator __last,
1672         _Size __count, const _Tp& __value_, _BinaryPredicate __pred)
1673{
1674    return _VSTD::__search_n<typename add_lvalue_reference<_BinaryPredicate>::type>
1675           (__first, __last, __convert_to_integral(__count), __value_, __pred,
1676           typename iterator_traits<_ForwardIterator>::iterator_category());
1677}
1678
1679template <class _ForwardIterator, class _Size, class _Tp>
1680inline _LIBCPP_INLINE_VISIBILITY
1681_ForwardIterator
1682search_n(_ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_)
1683{
1684    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
1685    return _VSTD::search_n(__first, __last, __convert_to_integral(__count),
1686                           __value_, __equal_to<__v, _Tp>());
1687}
1688
1689// copy
1690
1691template <class _Iter>
1692struct __libcpp_is_trivial_iterator
1693{
1694    static const bool value = is_pointer<_Iter>::value;
1695};
1696
1697template <class _Iter>
1698struct __libcpp_is_trivial_iterator<move_iterator<_Iter> >
1699{
1700    static const bool value = is_pointer<_Iter>::value;
1701};
1702
1703template <class _Iter>
1704struct __libcpp_is_trivial_iterator<__wrap_iter<_Iter> >
1705{
1706    static const bool value = is_pointer<_Iter>::value;
1707};
1708
1709template <class _Iter>
1710inline _LIBCPP_INLINE_VISIBILITY
1711_Iter
1712__unwrap_iter(_Iter __i)
1713{
1714    return __i;
1715}
1716
1717template <class _Tp>
1718inline _LIBCPP_INLINE_VISIBILITY
1719typename enable_if
1720<
1721    is_trivially_copy_assignable<_Tp>::value,
1722    _Tp*
1723>::type
1724__unwrap_iter(move_iterator<_Tp*> __i)
1725{
1726    return __i.base();
1727}
1728
1729#if _LIBCPP_DEBUG_LEVEL < 2
1730
1731template <class _Tp>
1732inline _LIBCPP_INLINE_VISIBILITY
1733typename enable_if
1734<
1735    is_trivially_copy_assignable<_Tp>::value,
1736    _Tp*
1737>::type
1738__unwrap_iter(__wrap_iter<_Tp*> __i)
1739{
1740    return __i.base();
1741}
1742
1743#endif  // _LIBCPP_DEBUG_LEVEL < 2
1744
1745template <class _InputIterator, class _OutputIterator>
1746inline _LIBCPP_INLINE_VISIBILITY
1747_OutputIterator
1748__copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
1749{
1750    for (; __first != __last; ++__first, (void) ++__result)
1751        *__result = *__first;
1752    return __result;
1753}
1754
1755template <class _Tp, class _Up>
1756inline _LIBCPP_INLINE_VISIBILITY
1757typename enable_if
1758<
1759    is_same<typename remove_const<_Tp>::type, _Up>::value &&
1760    is_trivially_copy_assignable<_Up>::value,
1761    _Up*
1762>::type
1763__copy(_Tp* __first, _Tp* __last, _Up* __result)
1764{
1765    const size_t __n = static_cast<size_t>(__last - __first);
1766    _VSTD::memmove(__result, __first, __n * sizeof(_Up));
1767    return __result + __n;
1768}
1769
1770template <class _InputIterator, class _OutputIterator>
1771inline _LIBCPP_INLINE_VISIBILITY
1772_OutputIterator
1773copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
1774{
1775    return _VSTD::__copy(__unwrap_iter(__first), __unwrap_iter(__last), __unwrap_iter(__result));
1776}
1777
1778// copy_backward
1779
1780template <class _BidirectionalIterator, class _OutputIterator>
1781inline _LIBCPP_INLINE_VISIBILITY
1782_OutputIterator
1783__copy_backward(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
1784{
1785    while (__first != __last)
1786        *--__result = *--__last;
1787    return __result;
1788}
1789
1790template <class _Tp, class _Up>
1791inline _LIBCPP_INLINE_VISIBILITY
1792typename enable_if
1793<
1794    is_same<typename remove_const<_Tp>::type, _Up>::value &&
1795    is_trivially_copy_assignable<_Up>::value,
1796    _Up*
1797>::type
1798__copy_backward(_Tp* __first, _Tp* __last, _Up* __result)
1799{
1800    const size_t __n = static_cast<size_t>(__last - __first);
1801    __result -= __n;
1802    _VSTD::memmove(__result, __first, __n * sizeof(_Up));
1803    return __result;
1804}
1805
1806template <class _BidirectionalIterator1, class _BidirectionalIterator2>
1807inline _LIBCPP_INLINE_VISIBILITY
1808_BidirectionalIterator2
1809copy_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
1810              _BidirectionalIterator2 __result)
1811{
1812    return _VSTD::__copy_backward(__unwrap_iter(__first), __unwrap_iter(__last), __unwrap_iter(__result));
1813}
1814
1815// copy_if
1816
1817template<class _InputIterator, class _OutputIterator, class _Predicate>
1818inline _LIBCPP_INLINE_VISIBILITY
1819_OutputIterator
1820copy_if(_InputIterator __first, _InputIterator __last,
1821        _OutputIterator __result, _Predicate __pred)
1822{
1823    for (; __first != __last; ++__first)
1824    {
1825        if (__pred(*__first))
1826        {
1827            *__result = *__first;
1828            ++__result;
1829        }
1830    }
1831    return __result;
1832}
1833
1834// copy_n
1835
1836template<class _InputIterator, class _Size, class _OutputIterator>
1837inline _LIBCPP_INLINE_VISIBILITY
1838typename enable_if
1839<
1840    __is_input_iterator<_InputIterator>::value &&
1841   !__is_random_access_iterator<_InputIterator>::value,
1842    _OutputIterator
1843>::type
1844copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
1845{
1846    typedef decltype(__convert_to_integral(__orig_n)) _IntegralSize;
1847    _IntegralSize __n = __orig_n;
1848    if (__n > 0)
1849    {
1850        *__result = *__first;
1851        ++__result;
1852        for (--__n; __n > 0; --__n)
1853        {
1854            ++__first;
1855            *__result = *__first;
1856            ++__result;
1857        }
1858    }
1859    return __result;
1860}
1861
1862template<class _InputIterator, class _Size, class _OutputIterator>
1863inline _LIBCPP_INLINE_VISIBILITY
1864typename enable_if
1865<
1866    __is_random_access_iterator<_InputIterator>::value,
1867    _OutputIterator
1868>::type
1869copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
1870{
1871    typedef decltype(__convert_to_integral(__orig_n)) _IntegralSize;
1872    _IntegralSize __n = __orig_n;
1873    return _VSTD::copy(__first, __first + __n, __result);
1874}
1875
1876// move
1877
1878template <class _InputIterator, class _OutputIterator>
1879inline _LIBCPP_INLINE_VISIBILITY
1880_OutputIterator
1881__move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
1882{
1883    for (; __first != __last; ++__first, (void) ++__result)
1884        *__result = _VSTD::move(*__first);
1885    return __result;
1886}
1887
1888template <class _Tp, class _Up>
1889inline _LIBCPP_INLINE_VISIBILITY
1890typename enable_if
1891<
1892    is_same<typename remove_const<_Tp>::type, _Up>::value &&
1893    is_trivially_copy_assignable<_Up>::value,
1894    _Up*
1895>::type
1896__move(_Tp* __first, _Tp* __last, _Up* __result)
1897{
1898    const size_t __n = static_cast<size_t>(__last - __first);
1899    _VSTD::memmove(__result, __first, __n * sizeof(_Up));
1900    return __result + __n;
1901}
1902
1903template <class _InputIterator, class _OutputIterator>
1904inline _LIBCPP_INLINE_VISIBILITY
1905_OutputIterator
1906move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
1907{
1908    return _VSTD::__move(__unwrap_iter(__first), __unwrap_iter(__last), __unwrap_iter(__result));
1909}
1910
1911// move_backward
1912
1913template <class _InputIterator, class _OutputIterator>
1914inline _LIBCPP_INLINE_VISIBILITY
1915_OutputIterator
1916__move_backward(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
1917{
1918    while (__first != __last)
1919        *--__result = _VSTD::move(*--__last);
1920    return __result;
1921}
1922
1923template <class _Tp, class _Up>
1924inline _LIBCPP_INLINE_VISIBILITY
1925typename enable_if
1926<
1927    is_same<typename remove_const<_Tp>::type, _Up>::value &&
1928    is_trivially_copy_assignable<_Up>::value,
1929    _Up*
1930>::type
1931__move_backward(_Tp* __first, _Tp* __last, _Up* __result)
1932{
1933    const size_t __n = static_cast<size_t>(__last - __first);
1934    __result -= __n;
1935    _VSTD::memmove(__result, __first, __n * sizeof(_Up));
1936    return __result;
1937}
1938
1939template <class _BidirectionalIterator1, class _BidirectionalIterator2>
1940inline _LIBCPP_INLINE_VISIBILITY
1941_BidirectionalIterator2
1942move_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
1943              _BidirectionalIterator2 __result)
1944{
1945    return _VSTD::__move_backward(__unwrap_iter(__first), __unwrap_iter(__last), __unwrap_iter(__result));
1946}
1947
1948// iter_swap
1949
1950// moved to <type_traits> for better swap / noexcept support
1951
1952// transform
1953
1954template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
1955inline _LIBCPP_INLINE_VISIBILITY
1956_OutputIterator
1957transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
1958{
1959    for (; __first != __last; ++__first, (void) ++__result)
1960        *__result = __op(*__first);
1961    return __result;
1962}
1963
1964template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _BinaryOperation>
1965inline _LIBCPP_INLINE_VISIBILITY
1966_OutputIterator
1967transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
1968          _OutputIterator __result, _BinaryOperation __binary_op)
1969{
1970    for (; __first1 != __last1; ++__first1, (void) ++__first2, ++__result)
1971        *__result = __binary_op(*__first1, *__first2);
1972    return __result;
1973}
1974
1975// replace
1976
1977template <class _ForwardIterator, class _Tp>
1978inline _LIBCPP_INLINE_VISIBILITY
1979void
1980replace(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __old_value, const _Tp& __new_value)
1981{
1982    for (; __first != __last; ++__first)
1983        if (*__first == __old_value)
1984            *__first = __new_value;
1985}
1986
1987// replace_if
1988
1989template <class _ForwardIterator, class _Predicate, class _Tp>
1990inline _LIBCPP_INLINE_VISIBILITY
1991void
1992replace_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, const _Tp& __new_value)
1993{
1994    for (; __first != __last; ++__first)
1995        if (__pred(*__first))
1996            *__first = __new_value;
1997}
1998
1999// replace_copy
2000
2001template <class _InputIterator, class _OutputIterator, class _Tp>
2002inline _LIBCPP_INLINE_VISIBILITY
2003_OutputIterator
2004replace_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
2005             const _Tp& __old_value, const _Tp& __new_value)
2006{
2007    for (; __first != __last; ++__first, (void) ++__result)
2008        if (*__first == __old_value)
2009            *__result = __new_value;
2010        else
2011            *__result = *__first;
2012    return __result;
2013}
2014
2015// replace_copy_if
2016
2017template <class _InputIterator, class _OutputIterator, class _Predicate, class _Tp>
2018inline _LIBCPP_INLINE_VISIBILITY
2019_OutputIterator
2020replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
2021                _Predicate __pred, const _Tp& __new_value)
2022{
2023    for (; __first != __last; ++__first, (void) ++__result)
2024        if (__pred(*__first))
2025            *__result = __new_value;
2026        else
2027            *__result = *__first;
2028    return __result;
2029}
2030
2031// fill_n
2032
2033template <class _OutputIterator, class _Size, class _Tp>
2034inline _LIBCPP_INLINE_VISIBILITY
2035_OutputIterator
2036__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
2037{
2038    for (; __n > 0; ++__first, (void) --__n)
2039        *__first = __value_;
2040    return __first;
2041}
2042
2043template <class _Tp, class _Size, class _Up>
2044inline _LIBCPP_INLINE_VISIBILITY
2045typename enable_if
2046<
2047    is_integral<_Tp>::value && sizeof(_Tp) == 1 &&
2048    !is_same<_Tp, bool>::value &&
2049    is_integral<_Up>::value && sizeof(_Up) == 1,
2050    _Tp*
2051>::type
2052__fill_n(_Tp* __first, _Size __n,_Up __value_)
2053{
2054    if (__n > 0)
2055        _VSTD::memset(__first, (unsigned char)__value_, (size_t)(__n));
2056    return __first + __n;
2057}
2058
2059template <class _OutputIterator, class _Size, class _Tp>
2060inline _LIBCPP_INLINE_VISIBILITY
2061_OutputIterator
2062fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
2063{
2064   return _VSTD::__fill_n(__first, __convert_to_integral(__n), __value_);
2065}
2066
2067// fill
2068
2069template <class _ForwardIterator, class _Tp>
2070inline _LIBCPP_INLINE_VISIBILITY
2071void
2072__fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, forward_iterator_tag)
2073{
2074    for (; __first != __last; ++__first)
2075        *__first = __value_;
2076}
2077
2078template <class _RandomAccessIterator, class _Tp>
2079inline _LIBCPP_INLINE_VISIBILITY
2080void
2081__fill(_RandomAccessIterator __first, _RandomAccessIterator __last, const _Tp& __value_, random_access_iterator_tag)
2082{
2083    _VSTD::fill_n(__first, __last - __first, __value_);
2084}
2085
2086template <class _ForwardIterator, class _Tp>
2087inline _LIBCPP_INLINE_VISIBILITY
2088void
2089fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
2090{
2091    _VSTD::__fill(__first, __last, __value_, typename iterator_traits<_ForwardIterator>::iterator_category());
2092}
2093
2094// generate
2095
2096template <class _ForwardIterator, class _Generator>
2097inline _LIBCPP_INLINE_VISIBILITY
2098void
2099generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen)
2100{
2101    for (; __first != __last; ++__first)
2102        *__first = __gen();
2103}
2104
2105// generate_n
2106
2107template <class _OutputIterator, class _Size, class _Generator>
2108inline _LIBCPP_INLINE_VISIBILITY
2109_OutputIterator
2110generate_n(_OutputIterator __first, _Size __orig_n, _Generator __gen)
2111{
2112    typedef decltype(__convert_to_integral(__orig_n)) _IntegralSize;
2113    _IntegralSize __n = __orig_n;
2114    for (; __n > 0; ++__first, (void) --__n)
2115        *__first = __gen();
2116    return __first;
2117}
2118
2119// remove
2120
2121template <class _ForwardIterator, class _Tp>
2122_ForwardIterator
2123remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
2124{
2125    __first = _VSTD::find(__first, __last, __value_);
2126    if (__first != __last)
2127    {
2128        _ForwardIterator __i = __first;
2129        while (++__i != __last)
2130        {
2131            if (!(*__i == __value_))
2132            {
2133                *__first = _VSTD::move(*__i);
2134                ++__first;
2135            }
2136        }
2137    }
2138    return __first;
2139}
2140
2141// remove_if
2142
2143template <class _ForwardIterator, class _Predicate>
2144_ForwardIterator
2145remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
2146{
2147    __first = _VSTD::find_if<_ForwardIterator, typename add_lvalue_reference<_Predicate>::type>
2148                           (__first, __last, __pred);
2149    if (__first != __last)
2150    {
2151        _ForwardIterator __i = __first;
2152        while (++__i != __last)
2153        {
2154            if (!__pred(*__i))
2155            {
2156                *__first = _VSTD::move(*__i);
2157                ++__first;
2158            }
2159        }
2160    }
2161    return __first;
2162}
2163
2164// remove_copy
2165
2166template <class _InputIterator, class _OutputIterator, class _Tp>
2167inline _LIBCPP_INLINE_VISIBILITY
2168_OutputIterator
2169remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value_)
2170{
2171    for (; __first != __last; ++__first)
2172    {
2173        if (!(*__first == __value_))
2174        {
2175            *__result = *__first;
2176            ++__result;
2177        }
2178    }
2179    return __result;
2180}
2181
2182// remove_copy_if
2183
2184template <class _InputIterator, class _OutputIterator, class _Predicate>
2185inline _LIBCPP_INLINE_VISIBILITY
2186_OutputIterator
2187remove_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred)
2188{
2189    for (; __first != __last; ++__first)
2190    {
2191        if (!__pred(*__first))
2192        {
2193            *__result = *__first;
2194            ++__result;
2195        }
2196    }
2197    return __result;
2198}
2199
2200// unique
2201
2202template <class _ForwardIterator, class _BinaryPredicate>
2203_ForwardIterator
2204unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
2205{
2206    __first = _VSTD::adjacent_find<_ForwardIterator, typename add_lvalue_reference<_BinaryPredicate>::type>
2207                                 (__first, __last, __pred);
2208    if (__first != __last)
2209    {
2210        // ...  a  a  ?  ...
2211        //      f     i
2212        _ForwardIterator __i = __first;
2213        for (++__i; ++__i != __last;)
2214            if (!__pred(*__first, *__i))
2215                *++__first = _VSTD::move(*__i);
2216        ++__first;
2217    }
2218    return __first;
2219}
2220
2221template <class _ForwardIterator>
2222inline _LIBCPP_INLINE_VISIBILITY
2223_ForwardIterator
2224unique(_ForwardIterator __first, _ForwardIterator __last)
2225{
2226    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
2227    return _VSTD::unique(__first, __last, __equal_to<__v>());
2228}
2229
2230// unique_copy
2231
2232template <class _BinaryPredicate, class _InputIterator, class _OutputIterator>
2233_OutputIterator
2234__unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
2235              input_iterator_tag, output_iterator_tag)
2236{
2237    if (__first != __last)
2238    {
2239        typename iterator_traits<_InputIterator>::value_type __t(*__first);
2240        *__result = __t;
2241        ++__result;
2242        while (++__first != __last)
2243        {
2244            if (!__pred(__t, *__first))
2245            {
2246                __t = *__first;
2247                *__result = __t;
2248                ++__result;
2249            }
2250        }
2251    }
2252    return __result;
2253}
2254
2255template <class _BinaryPredicate, class _ForwardIterator, class _OutputIterator>
2256_OutputIterator
2257__unique_copy(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
2258              forward_iterator_tag, output_iterator_tag)
2259{
2260    if (__first != __last)
2261    {
2262        _ForwardIterator __i = __first;
2263        *__result = *__i;
2264        ++__result;
2265        while (++__first != __last)
2266        {
2267            if (!__pred(*__i, *__first))
2268            {
2269                *__result = *__first;
2270                ++__result;
2271                __i = __first;
2272            }
2273        }
2274    }
2275    return __result;
2276}
2277
2278template <class _BinaryPredicate, class _InputIterator, class _ForwardIterator>
2279_ForwardIterator
2280__unique_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _BinaryPredicate __pred,
2281              input_iterator_tag, forward_iterator_tag)
2282{
2283    if (__first != __last)
2284    {
2285        *__result = *__first;
2286        while (++__first != __last)
2287            if (!__pred(*__result, *__first))
2288                *++__result = *__first;
2289        ++__result;
2290    }
2291    return __result;
2292}
2293
2294template <class _InputIterator, class _OutputIterator, class _BinaryPredicate>
2295inline _LIBCPP_INLINE_VISIBILITY
2296_OutputIterator
2297unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred)
2298{
2299    return _VSTD::__unique_copy<typename add_lvalue_reference<_BinaryPredicate>::type>
2300                              (__first, __last, __result, __pred,
2301                               typename iterator_traits<_InputIterator>::iterator_category(),
2302                               typename iterator_traits<_OutputIterator>::iterator_category());
2303}
2304
2305template <class _InputIterator, class _OutputIterator>
2306inline _LIBCPP_INLINE_VISIBILITY
2307_OutputIterator
2308unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
2309{
2310    typedef typename iterator_traits<_InputIterator>::value_type __v;
2311    return _VSTD::unique_copy(__first, __last, __result, __equal_to<__v>());
2312}
2313
2314// reverse
2315
2316template <class _BidirectionalIterator>
2317inline _LIBCPP_INLINE_VISIBILITY
2318void
2319__reverse(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag)
2320{
2321    while (__first != __last)
2322    {
2323        if (__first == --__last)
2324            break;
2325        swap(*__first, *__last);
2326        ++__first;
2327    }
2328}
2329
2330template <class _RandomAccessIterator>
2331inline _LIBCPP_INLINE_VISIBILITY
2332void
2333__reverse(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag)
2334{
2335    if (__first != __last)
2336        for (; __first < --__last; ++__first)
2337            swap(*__first, *__last);
2338}
2339
2340template <class _BidirectionalIterator>
2341inline _LIBCPP_INLINE_VISIBILITY
2342void
2343reverse(_BidirectionalIterator __first, _BidirectionalIterator __last)
2344{
2345    _VSTD::__reverse(__first, __last, typename iterator_traits<_BidirectionalIterator>::iterator_category());
2346}
2347
2348// reverse_copy
2349
2350template <class _BidirectionalIterator, class _OutputIterator>
2351inline _LIBCPP_INLINE_VISIBILITY
2352_OutputIterator
2353reverse_copy(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
2354{
2355    for (; __first != __last; ++__result)
2356        *__result = *--__last;
2357    return __result;
2358}
2359
2360// rotate
2361
2362template <class _ForwardIterator>
2363_ForwardIterator
2364__rotate_left(_ForwardIterator __first, _ForwardIterator __last)
2365{
2366    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
2367    value_type __tmp = _VSTD::move(*__first);
2368    _ForwardIterator __lm1 = _VSTD::move(_VSTD::next(__first), __last, __first);
2369    *__lm1 = _VSTD::move(__tmp);
2370    return __lm1;
2371}
2372
2373template <class _BidirectionalIterator>
2374_BidirectionalIterator
2375__rotate_right(_BidirectionalIterator __first, _BidirectionalIterator __last)
2376{
2377    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
2378    _BidirectionalIterator __lm1 = _VSTD::prev(__last);
2379    value_type __tmp = _VSTD::move(*__lm1);
2380    _BidirectionalIterator __fp1 = _VSTD::move_backward(__first, __lm1, __last);
2381    *__first = _VSTD::move(__tmp);
2382    return __fp1;
2383}
2384
2385template <class _ForwardIterator>
2386_ForwardIterator
2387__rotate_forward(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
2388{
2389    _ForwardIterator __i = __middle;
2390    while (true)
2391    {
2392        swap(*__first, *__i);
2393        ++__first;
2394        if (++__i == __last)
2395            break;
2396        if (__first == __middle)
2397            __middle = __i;
2398    }
2399    _ForwardIterator __r = __first;
2400    if (__first != __middle)
2401    {
2402        __i = __middle;
2403        while (true)
2404        {
2405            swap(*__first, *__i);
2406            ++__first;
2407            if (++__i == __last)
2408            {
2409                if (__first == __middle)
2410                    break;
2411                __i = __middle;
2412            }
2413            else if (__first == __middle)
2414                __middle = __i;
2415        }
2416    }
2417    return __r;
2418}
2419
2420template<typename _Integral>
2421inline _LIBCPP_INLINE_VISIBILITY
2422_Integral
2423__gcd(_Integral __x, _Integral __y)
2424{
2425    do
2426    {
2427        _Integral __t = __x % __y;
2428        __x = __y;
2429        __y = __t;
2430    } while (__y);
2431    return __x;
2432}
2433
2434template<typename _RandomAccessIterator>
2435_RandomAccessIterator
2436__rotate_gcd(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
2437{
2438    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
2439    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
2440
2441    const difference_type __m1 = __middle - __first;
2442    const difference_type __m2 = __last - __middle;
2443    if (__m1 == __m2)
2444    {
2445        _VSTD::swap_ranges(__first, __middle, __middle);
2446        return __middle;
2447    }
2448    const difference_type __g = _VSTD::__gcd(__m1, __m2);
2449    for (_RandomAccessIterator __p = __first + __g; __p != __first;)
2450    {
2451        value_type __t(_VSTD::move(*--__p));
2452        _RandomAccessIterator __p1 = __p;
2453        _RandomAccessIterator __p2 = __p1 + __m1;
2454        do
2455        {
2456            *__p1 = _VSTD::move(*__p2);
2457            __p1 = __p2;
2458            const difference_type __d = __last - __p2;
2459            if (__m1 < __d)
2460                __p2 += __m1;
2461            else
2462                __p2 = __first + (__m1 - __d);
2463        } while (__p2 != __p);
2464        *__p1 = _VSTD::move(__t);
2465    }
2466    return __first + __m2;
2467}
2468
2469template <class _ForwardIterator>
2470inline _LIBCPP_INLINE_VISIBILITY
2471_ForwardIterator
2472__rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last,
2473         _VSTD::forward_iterator_tag)
2474{
2475    typedef typename _VSTD::iterator_traits<_ForwardIterator>::value_type value_type;
2476    if (_VSTD::is_trivially_move_assignable<value_type>::value)
2477    {
2478        if (_VSTD::next(__first) == __middle)
2479            return _VSTD::__rotate_left(__first, __last);
2480    }
2481    return _VSTD::__rotate_forward(__first, __middle, __last);
2482}
2483
2484template <class _BidirectionalIterator>
2485inline _LIBCPP_INLINE_VISIBILITY
2486_BidirectionalIterator
2487__rotate(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
2488         _VSTD::bidirectional_iterator_tag)
2489{
2490    typedef typename _VSTD::iterator_traits<_BidirectionalIterator>::value_type value_type;
2491    if (_VSTD::is_trivially_move_assignable<value_type>::value)
2492    {
2493        if (_VSTD::next(__first) == __middle)
2494            return _VSTD::__rotate_left(__first, __last);
2495        if (_VSTD::next(__middle) == __last)
2496            return _VSTD::__rotate_right(__first, __last);
2497    }
2498    return _VSTD::__rotate_forward(__first, __middle, __last);
2499}
2500
2501template <class _RandomAccessIterator>
2502inline _LIBCPP_INLINE_VISIBILITY
2503_RandomAccessIterator
2504__rotate(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
2505         _VSTD::random_access_iterator_tag)
2506{
2507    typedef typename _VSTD::iterator_traits<_RandomAccessIterator>::value_type value_type;
2508    if (_VSTD::is_trivially_move_assignable<value_type>::value)
2509    {
2510        if (_VSTD::next(__first) == __middle)
2511            return _VSTD::__rotate_left(__first, __last);
2512        if (_VSTD::next(__middle) == __last)
2513            return _VSTD::__rotate_right(__first, __last);
2514        return _VSTD::__rotate_gcd(__first, __middle, __last);
2515    }
2516    return _VSTD::__rotate_forward(__first, __middle, __last);
2517}
2518
2519template <class _ForwardIterator>
2520inline _LIBCPP_INLINE_VISIBILITY
2521_ForwardIterator
2522rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
2523{
2524    if (__first == __middle)
2525        return __last;
2526    if (__middle == __last)
2527        return __first;
2528    return _VSTD::__rotate(__first, __middle, __last,
2529                           typename _VSTD::iterator_traits<_ForwardIterator>::iterator_category());
2530}
2531
2532// rotate_copy
2533
2534template <class _ForwardIterator, class _OutputIterator>
2535inline _LIBCPP_INLINE_VISIBILITY
2536_OutputIterator
2537rotate_copy(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last, _OutputIterator __result)
2538{
2539    return _VSTD::copy(__first, __middle, _VSTD::copy(__middle, __last, __result));
2540}
2541
2542// min_element
2543
2544template <class _ForwardIterator, class _Compare>
2545inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2546_ForwardIterator
2547min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
2548{
2549    if (__first != __last)
2550    {
2551        _ForwardIterator __i = __first;
2552        while (++__i != __last)
2553            if (__comp(*__i, *__first))
2554                __first = __i;
2555    }
2556    return __first;
2557}
2558
2559template <class _ForwardIterator>
2560inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2561_ForwardIterator
2562min_element(_ForwardIterator __first, _ForwardIterator __last)
2563{
2564    return _VSTD::min_element(__first, __last,
2565              __less<typename iterator_traits<_ForwardIterator>::value_type>());
2566}
2567
2568// min
2569
2570template <class _Tp, class _Compare>
2571inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2572const _Tp&
2573min(const _Tp& __a, const _Tp& __b, _Compare __comp)
2574{
2575    return __comp(__b, __a) ? __b : __a;
2576}
2577
2578template <class _Tp>
2579inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2580const _Tp&
2581min(const _Tp& __a, const _Tp& __b)
2582{
2583    return _VSTD::min(__a, __b, __less<_Tp>());
2584}
2585
2586#ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2587
2588template<class _Tp, class _Compare>
2589inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2590_Tp
2591min(initializer_list<_Tp> __t, _Compare __comp)
2592{
2593    return *_VSTD::min_element(__t.begin(), __t.end(), __comp);
2594}
2595
2596template<class _Tp>
2597inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2598_Tp
2599min(initializer_list<_Tp> __t)
2600{
2601    return *_VSTD::min_element(__t.begin(), __t.end(), __less<_Tp>());
2602}
2603
2604#endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2605
2606// max_element
2607
2608template <class _ForwardIterator, class _Compare>
2609inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2610_ForwardIterator
2611max_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
2612{
2613    if (__first != __last)
2614    {
2615        _ForwardIterator __i = __first;
2616        while (++__i != __last)
2617            if (__comp(*__first, *__i))
2618                __first = __i;
2619    }
2620    return __first;
2621}
2622
2623
2624template <class _ForwardIterator>
2625inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2626_ForwardIterator
2627max_element(_ForwardIterator __first, _ForwardIterator __last)
2628{
2629    return _VSTD::max_element(__first, __last,
2630              __less<typename iterator_traits<_ForwardIterator>::value_type>());
2631}
2632
2633// max
2634
2635template <class _Tp, class _Compare>
2636inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2637const _Tp&
2638max(const _Tp& __a, const _Tp& __b, _Compare __comp)
2639{
2640    return __comp(__a, __b) ? __b : __a;
2641}
2642
2643template <class _Tp>
2644inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2645const _Tp&
2646max(const _Tp& __a, const _Tp& __b)
2647{
2648    return _VSTD::max(__a, __b, __less<_Tp>());
2649}
2650
2651#ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2652
2653template<class _Tp, class _Compare>
2654inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2655_Tp
2656max(initializer_list<_Tp> __t, _Compare __comp)
2657{
2658    return *_VSTD::max_element(__t.begin(), __t.end(), __comp);
2659}
2660
2661template<class _Tp>
2662inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2663_Tp
2664max(initializer_list<_Tp> __t)
2665{
2666    return *_VSTD::max_element(__t.begin(), __t.end(), __less<_Tp>());
2667}
2668
2669#endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2670
2671// minmax_element
2672
2673template <class _ForwardIterator, class _Compare>
2674_LIBCPP_CONSTEXPR_AFTER_CXX11
2675std::pair<_ForwardIterator, _ForwardIterator>
2676minmax_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
2677{
2678  std::pair<_ForwardIterator, _ForwardIterator> __result(__first, __first);
2679  if (__first != __last)
2680  {
2681      if (++__first != __last)
2682      {
2683          if (__comp(*__first, *__result.first))
2684              __result.first = __first;
2685          else
2686              __result.second = __first;
2687          while (++__first != __last)
2688          {
2689              _ForwardIterator __i = __first;
2690              if (++__first == __last)
2691              {
2692                  if (__comp(*__i, *__result.first))
2693                      __result.first = __i;
2694                  else if (!__comp(*__i, *__result.second))
2695                      __result.second = __i;
2696                  break;
2697              }
2698              else
2699              {
2700                  if (__comp(*__first, *__i))
2701                  {
2702                      if (__comp(*__first, *__result.first))
2703                          __result.first = __first;
2704                      if (!__comp(*__i, *__result.second))
2705                          __result.second = __i;
2706                  }
2707                  else
2708                  {
2709                      if (__comp(*__i, *__result.first))
2710                          __result.first = __i;
2711                      if (!__comp(*__first, *__result.second))
2712                          __result.second = __first;
2713                  }
2714              }
2715          }
2716      }
2717  }
2718  return __result;
2719}
2720
2721template <class _ForwardIterator>
2722inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2723std::pair<_ForwardIterator, _ForwardIterator>
2724minmax_element(_ForwardIterator __first, _ForwardIterator __last)
2725{
2726    return _VSTD::minmax_element(__first, __last,
2727              __less<typename iterator_traits<_ForwardIterator>::value_type>());
2728}
2729
2730// minmax
2731
2732template<class _Tp, class _Compare>
2733inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2734pair<const _Tp&, const _Tp&>
2735minmax(const _Tp& __a, const _Tp& __b, _Compare __comp)
2736{
2737    return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) :
2738                              pair<const _Tp&, const _Tp&>(__a, __b);
2739}
2740
2741template<class _Tp>
2742inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2743pair<const _Tp&, const _Tp&>
2744minmax(const _Tp& __a, const _Tp& __b)
2745{
2746    return _VSTD::minmax(__a, __b, __less<_Tp>());
2747}
2748
2749#ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2750
2751template<class _Tp, class _Compare>
2752inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2753pair<_Tp, _Tp>
2754minmax(initializer_list<_Tp> __t, _Compare __comp)
2755{
2756    typedef typename initializer_list<_Tp>::const_iterator _Iter;
2757    _Iter __first = __t.begin();
2758    _Iter __last  = __t.end();
2759    std::pair<_Tp, _Tp> __result(*__first, *__first);
2760
2761    ++__first;
2762    if (__t.size() % 2 == 0)
2763    {
2764        if (__comp(*__first,  __result.first))
2765            __result.first  = *__first;
2766        else
2767            __result.second = *__first;
2768        ++__first;
2769    }
2770
2771    while (__first != __last)
2772    {
2773        _Tp __prev = *__first++;
2774        if (__comp(*__first, __prev)) {
2775            if ( __comp(*__first, __result.first)) __result.first  = *__first;
2776            if (!__comp(__prev, __result.second))  __result.second = __prev;
2777            }
2778        else {
2779            if ( __comp(__prev, __result.first))    __result.first  = __prev;
2780            if (!__comp(*__first, __result.second)) __result.second = *__first;
2781            }
2782
2783        __first++;
2784    }
2785    return __result;
2786}
2787
2788template<class _Tp>
2789inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
2790pair<_Tp, _Tp>
2791minmax(initializer_list<_Tp> __t)
2792{
2793    return _VSTD::minmax(__t, __less<_Tp>());
2794}
2795
2796#endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
2797
2798// random_shuffle
2799
2800// __independent_bits_engine
2801
2802template <unsigned long long _Xp, size_t _Rp>
2803struct __log2_imp
2804{
2805    static const size_t value = _Xp & ((unsigned long long)(1) << _Rp) ? _Rp
2806                                           : __log2_imp<_Xp, _Rp - 1>::value;
2807};
2808
2809template <unsigned long long _Xp>
2810struct __log2_imp<_Xp, 0>
2811{
2812    static const size_t value = 0;
2813};
2814
2815template <size_t _Rp>
2816struct __log2_imp<0, _Rp>
2817{
2818    static const size_t value = _Rp + 1;
2819};
2820
2821template <class _UI, _UI _Xp>
2822struct __log2
2823{
2824    static const size_t value = __log2_imp<_Xp,
2825                                         sizeof(_UI) * __CHAR_BIT__ - 1>::value;
2826};
2827
2828template<class _Engine, class _UIntType>
2829class __independent_bits_engine
2830{
2831public:
2832    // types
2833    typedef _UIntType result_type;
2834
2835private:
2836    typedef typename _Engine::result_type _Engine_result_type;
2837    typedef typename conditional
2838        <
2839            sizeof(_Engine_result_type) <= sizeof(result_type),
2840                result_type,
2841                _Engine_result_type
2842        >::type _Working_result_type;
2843
2844    _Engine& __e_;
2845    size_t __w_;
2846    size_t __w0_;
2847    size_t __n_;
2848    size_t __n0_;
2849    _Working_result_type __y0_;
2850    _Working_result_type __y1_;
2851    _Engine_result_type __mask0_;
2852    _Engine_result_type __mask1_;
2853
2854#ifdef _LIBCPP_HAS_NO_CONSTEXPR
2855    static const _Working_result_type _Rp = _Engine::_Max - _Engine::_Min
2856                                          + _Working_result_type(1);
2857#else
2858    static _LIBCPP_CONSTEXPR const _Working_result_type _Rp = _Engine::max() - _Engine::min()
2859                                                      + _Working_result_type(1);
2860#endif
2861    static _LIBCPP_CONSTEXPR const size_t __m = __log2<_Working_result_type, _Rp>::value;
2862    static _LIBCPP_CONSTEXPR const size_t _WDt = numeric_limits<_Working_result_type>::digits;
2863    static _LIBCPP_CONSTEXPR const size_t _EDt = numeric_limits<_Engine_result_type>::digits;
2864
2865public:
2866    // constructors and seeding functions
2867    __independent_bits_engine(_Engine& __e, size_t __w);
2868
2869    // generating functions
2870    result_type operator()() {return __eval(integral_constant<bool, _Rp != 0>());}
2871
2872private:
2873    result_type __eval(false_type);
2874    result_type __eval(true_type);
2875};
2876
2877template<class _Engine, class _UIntType>
2878__independent_bits_engine<_Engine, _UIntType>
2879    ::__independent_bits_engine(_Engine& __e, size_t __w)
2880        : __e_(__e),
2881          __w_(__w)
2882{
2883    __n_ = __w_ / __m + (__w_ % __m != 0);
2884    __w0_ = __w_ / __n_;
2885    if (_Rp == 0)
2886        __y0_ = _Rp;
2887    else if (__w0_ < _WDt)
2888        __y0_ = (_Rp >> __w0_) << __w0_;
2889    else
2890        __y0_ = 0;
2891    if (_Rp - __y0_ > __y0_ / __n_)
2892    {
2893        ++__n_;
2894        __w0_ = __w_ / __n_;
2895        if (__w0_ < _WDt)
2896            __y0_ = (_Rp >> __w0_) << __w0_;
2897        else
2898            __y0_ = 0;
2899    }
2900    __n0_ = __n_ - __w_ % __n_;
2901    if (__w0_ < _WDt - 1)
2902        __y1_ = (_Rp >> (__w0_ + 1)) << (__w0_ + 1);
2903    else
2904        __y1_ = 0;
2905    __mask0_ = __w0_ > 0 ? _Engine_result_type(~0) >> (_EDt - __w0_) :
2906                          _Engine_result_type(0);
2907    __mask1_ = __w0_ < _EDt - 1 ?
2908                               _Engine_result_type(~0) >> (_EDt - (__w0_ + 1)) :
2909                               _Engine_result_type(~0);
2910}
2911
2912template<class _Engine, class _UIntType>
2913inline
2914_UIntType
2915__independent_bits_engine<_Engine, _UIntType>::__eval(false_type)
2916{
2917    return static_cast<result_type>(__e_() & __mask0_);
2918}
2919
2920template<class _Engine, class _UIntType>
2921_UIntType
2922__independent_bits_engine<_Engine, _UIntType>::__eval(true_type)
2923{
2924    result_type _Sp = 0;
2925    for (size_t __k = 0; __k < __n0_; ++__k)
2926    {
2927        _Engine_result_type __u;
2928        do
2929        {
2930            __u = __e_() - _Engine::min();
2931        } while (__u >= __y0_);
2932        if (__w0_ < _WDt)
2933            _Sp <<= __w0_;
2934        else
2935            _Sp = 0;
2936        _Sp += __u & __mask0_;
2937    }
2938    for (size_t __k = __n0_; __k < __n_; ++__k)
2939    {
2940        _Engine_result_type __u;
2941        do
2942        {
2943            __u = __e_() - _Engine::min();
2944        } while (__u >= __y1_);
2945        if (__w0_ < _WDt - 1)
2946            _Sp <<= __w0_ + 1;
2947        else
2948            _Sp = 0;
2949        _Sp += __u & __mask1_;
2950    }
2951    return _Sp;
2952}
2953
2954// uniform_int_distribution
2955
2956template<class _IntType = int>
2957class uniform_int_distribution
2958{
2959public:
2960    // types
2961    typedef _IntType result_type;
2962
2963    class param_type
2964    {
2965        result_type __a_;
2966        result_type __b_;
2967    public:
2968        typedef uniform_int_distribution distribution_type;
2969
2970        explicit param_type(result_type __a = 0,
2971                            result_type __b = numeric_limits<result_type>::max())
2972            : __a_(__a), __b_(__b) {}
2973
2974        result_type a() const {return __a_;}
2975        result_type b() const {return __b_;}
2976
2977        friend bool operator==(const param_type& __x, const param_type& __y)
2978            {return __x.__a_ == __y.__a_ && __x.__b_ == __y.__b_;}
2979        friend bool operator!=(const param_type& __x, const param_type& __y)
2980            {return !(__x == __y);}
2981    };
2982
2983private:
2984    param_type __p_;
2985
2986public:
2987    // constructors and reset functions
2988    explicit uniform_int_distribution(result_type __a = 0,
2989                                      result_type __b = numeric_limits<result_type>::max())
2990        : __p_(param_type(__a, __b)) {}
2991    explicit uniform_int_distribution(const param_type& __p) : __p_(__p) {}
2992    void reset() {}
2993
2994    // generating functions
2995    template<class _URNG> result_type operator()(_URNG& __g)
2996        {return (*this)(__g, __p_);}
2997    template<class _URNG> result_type operator()(_URNG& __g, const param_type& __p);
2998
2999    // property functions
3000    result_type a() const {return __p_.a();}
3001    result_type b() const {return __p_.b();}
3002
3003    param_type param() const {return __p_;}
3004    void param(const param_type& __p) {__p_ = __p;}
3005
3006    result_type min() const {return a();}
3007    result_type max() const {return b();}
3008
3009    friend bool operator==(const uniform_int_distribution& __x,
3010                           const uniform_int_distribution& __y)
3011        {return __x.__p_ == __y.__p_;}
3012    friend bool operator!=(const uniform_int_distribution& __x,
3013                           const uniform_int_distribution& __y)
3014            {return !(__x == __y);}
3015};
3016
3017template<class _IntType>
3018template<class _URNG>
3019typename uniform_int_distribution<_IntType>::result_type
3020uniform_int_distribution<_IntType>::operator()(_URNG& __g, const param_type& __p)
3021{
3022    typedef typename conditional<sizeof(result_type) <= sizeof(uint32_t),
3023                                            uint32_t, uint64_t>::type _UIntType;
3024    const _UIntType _Rp = __p.b() - __p.a() + _UIntType(1);
3025    if (_Rp == 1)
3026        return __p.a();
3027    const size_t _Dt = numeric_limits<_UIntType>::digits;
3028    typedef __independent_bits_engine<_URNG, _UIntType> _Eng;
3029    if (_Rp == 0)
3030        return static_cast<result_type>(_Eng(__g, _Dt)());
3031    size_t __w = _Dt - __clz(_Rp) - 1;
3032    if ((_Rp & (_UIntType(~0) >> (_Dt - __w))) != 0)
3033        ++__w;
3034    _Eng __e(__g, __w);
3035    _UIntType __u;
3036    do
3037    {
3038        __u = __e();
3039    } while (__u >= _Rp);
3040    return static_cast<result_type>(__u + __p.a());
3041}
3042
3043class _LIBCPP_TYPE_VIS __rs_default;
3044
3045_LIBCPP_FUNC_VIS __rs_default __rs_get();
3046
3047class _LIBCPP_TYPE_VIS __rs_default
3048{
3049    static unsigned __c_;
3050
3051    __rs_default();
3052public:
3053    typedef uint_fast32_t result_type;
3054
3055    static const result_type _Min = 0;
3056    static const result_type _Max = 0xFFFFFFFF;
3057
3058    __rs_default(const __rs_default&);
3059    ~__rs_default();
3060
3061    result_type operator()();
3062
3063    static _LIBCPP_CONSTEXPR result_type min() {return _Min;}
3064    static _LIBCPP_CONSTEXPR result_type max() {return _Max;}
3065
3066    friend _LIBCPP_FUNC_VIS __rs_default __rs_get();
3067};
3068
3069_LIBCPP_FUNC_VIS __rs_default __rs_get();
3070
3071template <class _RandomAccessIterator>
3072void
3073random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last)
3074{
3075    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
3076    typedef uniform_int_distribution<ptrdiff_t> _Dp;
3077    typedef typename _Dp::param_type _Pp;
3078    difference_type __d = __last - __first;
3079    if (__d > 1)
3080    {
3081        _Dp __uid;
3082        __rs_default __g = __rs_get();
3083        for (--__last, --__d; __first < __last; ++__first, --__d)
3084        {
3085            difference_type __i = __uid(__g, _Pp(0, __d));
3086            if (__i != difference_type(0))
3087                swap(*__first, *(__first + __i));
3088        }
3089    }
3090}
3091
3092template <class _RandomAccessIterator, class _RandomNumberGenerator>
3093void
3094random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
3095#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
3096               _RandomNumberGenerator&& __rand)
3097#else
3098               _RandomNumberGenerator& __rand)
3099#endif
3100{
3101    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
3102    difference_type __d = __last - __first;
3103    if (__d > 1)
3104    {
3105        for (--__last; __first < __last; ++__first, --__d)
3106        {
3107            difference_type __i = __rand(__d);
3108            swap(*__first, *(__first + __i));
3109        }
3110    }
3111}
3112
3113template<class _RandomAccessIterator, class _UniformRandomNumberGenerator>
3114    void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
3115#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
3116                 _UniformRandomNumberGenerator&& __g)
3117#else
3118                 _UniformRandomNumberGenerator& __g)
3119#endif
3120{
3121    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
3122    typedef uniform_int_distribution<ptrdiff_t> _Dp;
3123    typedef typename _Dp::param_type _Pp;
3124    difference_type __d = __last - __first;
3125    if (__d > 1)
3126    {
3127        _Dp __uid;
3128        for (--__last, --__d; __first < __last; ++__first, --__d)
3129        {
3130            difference_type __i = __uid(__g, _Pp(0, __d));
3131            if (__i != difference_type(0))
3132                swap(*__first, *(__first + __i));
3133        }
3134    }
3135}
3136
3137template <class _InputIterator, class _Predicate>
3138bool
3139is_partitioned(_InputIterator __first, _InputIterator __last, _Predicate __pred)
3140{
3141    for (; __first != __last; ++__first)
3142        if (!__pred(*__first))
3143            break;
3144    if ( __first == __last )
3145        return true;
3146    ++__first;
3147    for (; __first != __last; ++__first)
3148        if (__pred(*__first))
3149            return false;
3150    return true;
3151}
3152
3153// partition
3154
3155template <class _Predicate, class _ForwardIterator>
3156_ForwardIterator
3157__partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, forward_iterator_tag)
3158{
3159    while (true)
3160    {
3161        if (__first == __last)
3162            return __first;
3163        if (!__pred(*__first))
3164            break;
3165        ++__first;
3166    }
3167    for (_ForwardIterator __p = __first; ++__p != __last;)
3168    {
3169        if (__pred(*__p))
3170        {
3171            swap(*__first, *__p);
3172            ++__first;
3173        }
3174    }
3175    return __first;
3176}
3177
3178template <class _Predicate, class _BidirectionalIterator>
3179_BidirectionalIterator
3180__partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
3181            bidirectional_iterator_tag)
3182{
3183    while (true)
3184    {
3185        while (true)
3186        {
3187            if (__first == __last)
3188                return __first;
3189            if (!__pred(*__first))
3190                break;
3191            ++__first;
3192        }
3193        do
3194        {
3195            if (__first == --__last)
3196                return __first;
3197        } while (!__pred(*__last));
3198        swap(*__first, *__last);
3199        ++__first;
3200    }
3201}
3202
3203template <class _ForwardIterator, class _Predicate>
3204inline _LIBCPP_INLINE_VISIBILITY
3205_ForwardIterator
3206partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
3207{
3208    return _VSTD::__partition<typename add_lvalue_reference<_Predicate>::type>
3209                            (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
3210}
3211
3212// partition_copy
3213
3214template <class _InputIterator, class _OutputIterator1,
3215          class _OutputIterator2, class _Predicate>
3216pair<_OutputIterator1, _OutputIterator2>
3217partition_copy(_InputIterator __first, _InputIterator __last,
3218               _OutputIterator1 __out_true, _OutputIterator2 __out_false,
3219               _Predicate __pred)
3220{
3221    for (; __first != __last; ++__first)
3222    {
3223        if (__pred(*__first))
3224        {
3225            *__out_true = *__first;
3226            ++__out_true;
3227        }
3228        else
3229        {
3230            *__out_false = *__first;
3231            ++__out_false;
3232        }
3233    }
3234    return pair<_OutputIterator1, _OutputIterator2>(__out_true, __out_false);
3235}
3236
3237// partition_point
3238
3239template<class _ForwardIterator, class _Predicate>
3240_ForwardIterator
3241partition_point(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
3242{
3243    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
3244    difference_type __len = _VSTD::distance(__first, __last);
3245    while (__len != 0)
3246    {
3247        difference_type __l2 = __len / 2;
3248        _ForwardIterator __m = __first;
3249        _VSTD::advance(__m, __l2);
3250        if (__pred(*__m))
3251        {
3252            __first = ++__m;
3253            __len -= __l2 + 1;
3254        }
3255        else
3256            __len = __l2;
3257    }
3258    return __first;
3259}
3260
3261// stable_partition
3262
3263template <class _Predicate, class _ForwardIterator, class _Distance, class _Pair>
3264_ForwardIterator
3265__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
3266                   _Distance __len, _Pair __p, forward_iterator_tag __fit)
3267{
3268    // *__first is known to be false
3269    // __len >= 1
3270    if (__len == 1)
3271        return __first;
3272    if (__len == 2)
3273    {
3274        _ForwardIterator __m = __first;
3275        if (__pred(*++__m))
3276        {
3277            swap(*__first, *__m);
3278            return __m;
3279        }
3280        return __first;
3281    }
3282    if (__len <= __p.second)
3283    {   // The buffer is big enough to use
3284        typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
3285        __destruct_n __d(0);
3286        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
3287        // Move the falses into the temporary buffer, and the trues to the front of the line
3288        // Update __first to always point to the end of the trues
3289        value_type* __t = __p.first;
3290        ::new(__t) value_type(_VSTD::move(*__first));
3291        __d.__incr((value_type*)0);
3292        ++__t;
3293        _ForwardIterator __i = __first;
3294        while (++__i != __last)
3295        {
3296            if (__pred(*__i))
3297            {
3298                *__first = _VSTD::move(*__i);
3299                ++__first;
3300            }
3301            else
3302            {
3303                ::new(__t) value_type(_VSTD::move(*__i));
3304                __d.__incr((value_type*)0);
3305                ++__t;
3306            }
3307        }
3308        // All trues now at start of range, all falses in buffer
3309        // Move falses back into range, but don't mess up __first which points to first false
3310        __i = __first;
3311        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, ++__i)
3312            *__i = _VSTD::move(*__t2);
3313        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
3314        return __first;
3315    }
3316    // Else not enough buffer, do in place
3317    // __len >= 3
3318    _ForwardIterator __m = __first;
3319    _Distance __len2 = __len / 2;  // __len2 >= 2
3320    _VSTD::advance(__m, __len2);
3321    // recurse on [__first, __m), *__first know to be false
3322    // F?????????????????
3323    // f       m         l
3324    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
3325    _ForwardIterator __first_false = __stable_partition<_PredRef>(__first, __m, __pred, __len2, __p, __fit);
3326    // TTTFFFFF??????????
3327    // f  ff   m         l
3328    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
3329    _ForwardIterator __m1 = __m;
3330    _ForwardIterator __second_false = __last;
3331    _Distance __len_half = __len - __len2;
3332    while (__pred(*__m1))
3333    {
3334        if (++__m1 == __last)
3335            goto __second_half_done;
3336        --__len_half;
3337    }
3338    // TTTFFFFFTTTF??????
3339    // f  ff   m  m1     l
3340    __second_false = __stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __fit);
3341__second_half_done:
3342    // TTTFFFFFTTTTTFFFFF
3343    // f  ff   m    sf   l
3344    return _VSTD::rotate(__first_false, __m, __second_false);
3345    // TTTTTTTTFFFFFFFFFF
3346    //         |
3347}
3348
3349struct __return_temporary_buffer
3350{
3351    template <class _Tp>
3352    _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __p) const {_VSTD::return_temporary_buffer(__p);}
3353};
3354
3355template <class _Predicate, class _ForwardIterator>
3356_ForwardIterator
3357__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
3358                   forward_iterator_tag)
3359{
3360    const unsigned __alloc_limit = 3;  // might want to make this a function of trivial assignment
3361    // Either prove all true and return __first or point to first false
3362    while (true)
3363    {
3364        if (__first == __last)
3365            return __first;
3366        if (!__pred(*__first))
3367            break;
3368        ++__first;
3369    }
3370    // We now have a reduced range [__first, __last)
3371    // *__first is known to be false
3372    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
3373    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
3374    difference_type __len = _VSTD::distance(__first, __last);
3375    pair<value_type*, ptrdiff_t> __p(0, 0);
3376    unique_ptr<value_type, __return_temporary_buffer> __h;
3377    if (__len >= __alloc_limit)
3378    {
3379        __p = _VSTD::get_temporary_buffer<value_type>(__len);
3380        __h.reset(__p.first);
3381    }
3382    return __stable_partition<typename add_lvalue_reference<_Predicate>::type>
3383                             (__first, __last, __pred, __len, __p, forward_iterator_tag());
3384}
3385
3386template <class _Predicate, class _BidirectionalIterator, class _Distance, class _Pair>
3387_BidirectionalIterator
3388__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
3389                   _Distance __len, _Pair __p, bidirectional_iterator_tag __bit)
3390{
3391    // *__first is known to be false
3392    // *__last is known to be true
3393    // __len >= 2
3394    if (__len == 2)
3395    {
3396        swap(*__first, *__last);
3397        return __last;
3398    }
3399    if (__len == 3)
3400    {
3401        _BidirectionalIterator __m = __first;
3402        if (__pred(*++__m))
3403        {
3404            swap(*__first, *__m);
3405            swap(*__m, *__last);
3406            return __last;
3407        }
3408        swap(*__m, *__last);
3409        swap(*__first, *__m);
3410        return __m;
3411    }
3412    if (__len <= __p.second)
3413    {   // The buffer is big enough to use
3414        typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
3415        __destruct_n __d(0);
3416        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
3417        // Move the falses into the temporary buffer, and the trues to the front of the line
3418        // Update __first to always point to the end of the trues
3419        value_type* __t = __p.first;
3420        ::new(__t) value_type(_VSTD::move(*__first));
3421        __d.__incr((value_type*)0);
3422        ++__t;
3423        _BidirectionalIterator __i = __first;
3424        while (++__i != __last)
3425        {
3426            if (__pred(*__i))
3427            {
3428                *__first = _VSTD::move(*__i);
3429                ++__first;
3430            }
3431            else
3432            {
3433                ::new(__t) value_type(_VSTD::move(*__i));
3434                __d.__incr((value_type*)0);
3435                ++__t;
3436            }
3437        }
3438        // move *__last, known to be true
3439        *__first = _VSTD::move(*__i);
3440        __i = ++__first;
3441        // All trues now at start of range, all falses in buffer
3442        // Move falses back into range, but don't mess up __first which points to first false
3443        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, ++__i)
3444            *__i = _VSTD::move(*__t2);
3445        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
3446        return __first;
3447    }
3448    // Else not enough buffer, do in place
3449    // __len >= 4
3450    _BidirectionalIterator __m = __first;
3451    _Distance __len2 = __len / 2;  // __len2 >= 2
3452    _VSTD::advance(__m, __len2);
3453    // recurse on [__first, __m-1], except reduce __m-1 until *(__m-1) is true, *__first know to be false
3454    // F????????????????T
3455    // f       m        l
3456    _BidirectionalIterator __m1 = __m;
3457    _BidirectionalIterator __first_false = __first;
3458    _Distance __len_half = __len2;
3459    while (!__pred(*--__m1))
3460    {
3461        if (__m1 == __first)
3462            goto __first_half_done;
3463        --__len_half;
3464    }
3465    // F???TFFF?????????T
3466    // f   m1  m        l
3467    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
3468    __first_false = __stable_partition<_PredRef>(__first, __m1, __pred, __len_half, __p, __bit);
3469__first_half_done:
3470    // TTTFFFFF?????????T
3471    // f  ff   m        l
3472    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
3473    __m1 = __m;
3474    _BidirectionalIterator __second_false = __last;
3475    ++__second_false;
3476    __len_half = __len - __len2;
3477    while (__pred(*__m1))
3478    {
3479        if (++__m1 == __last)
3480            goto __second_half_done;
3481        --__len_half;
3482    }
3483    // TTTFFFFFTTTF?????T
3484    // f  ff   m  m1    l
3485    __second_false = __stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __bit);
3486__second_half_done:
3487    // TTTFFFFFTTTTTFFFFF
3488    // f  ff   m    sf  l
3489    return _VSTD::rotate(__first_false, __m, __second_false);
3490    // TTTTTTTTFFFFFFFFFF
3491    //         |
3492}
3493
3494template <class _Predicate, class _BidirectionalIterator>
3495_BidirectionalIterator
3496__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
3497                   bidirectional_iterator_tag)
3498{
3499    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
3500    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
3501    const difference_type __alloc_limit = 4;  // might want to make this a function of trivial assignment
3502    // Either prove all true and return __first or point to first false
3503    while (true)
3504    {
3505        if (__first == __last)
3506            return __first;
3507        if (!__pred(*__first))
3508            break;
3509        ++__first;
3510    }
3511    // __first points to first false, everything prior to __first is already set.
3512    // Either prove [__first, __last) is all false and return __first, or point __last to last true
3513    do
3514    {
3515        if (__first == --__last)
3516            return __first;
3517    } while (!__pred(*__last));
3518    // We now have a reduced range [__first, __last]
3519    // *__first is known to be false
3520    // *__last is known to be true
3521    // __len >= 2
3522    difference_type __len = _VSTD::distance(__first, __last) + 1;
3523    pair<value_type*, ptrdiff_t> __p(0, 0);
3524    unique_ptr<value_type, __return_temporary_buffer> __h;
3525    if (__len >= __alloc_limit)
3526    {
3527        __p = _VSTD::get_temporary_buffer<value_type>(__len);
3528        __h.reset(__p.first);
3529    }
3530    return __stable_partition<typename add_lvalue_reference<_Predicate>::type>
3531                             (__first, __last, __pred, __len, __p, bidirectional_iterator_tag());
3532}
3533
3534template <class _ForwardIterator, class _Predicate>
3535inline _LIBCPP_INLINE_VISIBILITY
3536_ForwardIterator
3537stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
3538{
3539    return __stable_partition<typename add_lvalue_reference<_Predicate>::type>
3540                             (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
3541}
3542
3543// is_sorted_until
3544
3545template <class _ForwardIterator, class _Compare>
3546_ForwardIterator
3547is_sorted_until(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
3548{
3549    if (__first != __last)
3550    {
3551        _ForwardIterator __i = __first;
3552        while (++__i != __last)
3553        {
3554            if (__comp(*__i, *__first))
3555                return __i;
3556            __first = __i;
3557        }
3558    }
3559    return __last;
3560}
3561
3562template<class _ForwardIterator>
3563inline _LIBCPP_INLINE_VISIBILITY
3564_ForwardIterator
3565is_sorted_until(_ForwardIterator __first, _ForwardIterator __last)
3566{
3567    return _VSTD::is_sorted_until(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
3568}
3569
3570// is_sorted
3571
3572template <class _ForwardIterator, class _Compare>
3573inline _LIBCPP_INLINE_VISIBILITY
3574bool
3575is_sorted(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
3576{
3577    return _VSTD::is_sorted_until(__first, __last, __comp) == __last;
3578}
3579
3580template<class _ForwardIterator>
3581inline _LIBCPP_INLINE_VISIBILITY
3582bool
3583is_sorted(_ForwardIterator __first, _ForwardIterator __last)
3584{
3585    return _VSTD::is_sorted(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
3586}
3587
3588// sort
3589
3590// stable, 2-3 compares, 0-2 swaps
3591
3592template <class _Compare, class _ForwardIterator>
3593unsigned
3594__sort3(_ForwardIterator __x, _ForwardIterator __y, _ForwardIterator __z, _Compare __c)
3595{
3596    unsigned __r = 0;
3597    if (!__c(*__y, *__x))          // if x <= y
3598    {
3599        if (!__c(*__z, *__y))      // if y <= z
3600            return __r;            // x <= y && y <= z
3601                                   // x <= y && y > z
3602        swap(*__y, *__z);          // x <= z && y < z
3603        __r = 1;
3604        if (__c(*__y, *__x))       // if x > y
3605        {
3606            swap(*__x, *__y);      // x < y && y <= z
3607            __r = 2;
3608        }
3609        return __r;                // x <= y && y < z
3610    }
3611    if (__c(*__z, *__y))           // x > y, if y > z
3612    {
3613        swap(*__x, *__z);          // x < y && y < z
3614        __r = 1;
3615        return __r;
3616    }
3617    swap(*__x, *__y);              // x > y && y <= z
3618    __r = 1;                       // x < y && x <= z
3619    if (__c(*__z, *__y))           // if y > z
3620    {
3621        swap(*__y, *__z);          // x <= y && y < z
3622        __r = 2;
3623    }
3624    return __r;
3625}                                  // x <= y && y <= z
3626
3627// stable, 3-6 compares, 0-5 swaps
3628
3629template <class _Compare, class _ForwardIterator>
3630unsigned
3631__sort4(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
3632            _ForwardIterator __x4, _Compare __c)
3633{
3634    unsigned __r = __sort3<_Compare>(__x1, __x2, __x3, __c);
3635    if (__c(*__x4, *__x3))
3636    {
3637        swap(*__x3, *__x4);
3638        ++__r;
3639        if (__c(*__x3, *__x2))
3640        {
3641            swap(*__x2, *__x3);
3642            ++__r;
3643            if (__c(*__x2, *__x1))
3644            {
3645                swap(*__x1, *__x2);
3646                ++__r;
3647            }
3648        }
3649    }
3650    return __r;
3651}
3652
3653// stable, 4-10 compares, 0-9 swaps
3654
3655template <class _Compare, class _ForwardIterator>
3656unsigned
3657__sort5(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
3658            _ForwardIterator __x4, _ForwardIterator __x5, _Compare __c)
3659{
3660    unsigned __r = __sort4<_Compare>(__x1, __x2, __x3, __x4, __c);
3661    if (__c(*__x5, *__x4))
3662    {
3663        swap(*__x4, *__x5);
3664        ++__r;
3665        if (__c(*__x4, *__x3))
3666        {
3667            swap(*__x3, *__x4);
3668            ++__r;
3669            if (__c(*__x3, *__x2))
3670            {
3671                swap(*__x2, *__x3);
3672                ++__r;
3673                if (__c(*__x2, *__x1))
3674                {
3675                    swap(*__x1, *__x2);
3676                    ++__r;
3677                }
3678            }
3679        }
3680    }
3681    return __r;
3682}
3683
3684// Assumes size > 0
3685template <class _Compare, class _BirdirectionalIterator>
3686void
3687__selection_sort(_BirdirectionalIterator __first, _BirdirectionalIterator __last, _Compare __comp)
3688{
3689    _BirdirectionalIterator __lm1 = __last;
3690    for (--__lm1; __first != __lm1; ++__first)
3691    {
3692        _BirdirectionalIterator __i = _VSTD::min_element<_BirdirectionalIterator,
3693                                                        typename add_lvalue_reference<_Compare>::type>
3694                                                       (__first, __last, __comp);
3695        if (__i != __first)
3696            swap(*__first, *__i);
3697    }
3698}
3699
3700template <class _Compare, class _BirdirectionalIterator>
3701void
3702__insertion_sort(_BirdirectionalIterator __first, _BirdirectionalIterator __last, _Compare __comp)
3703{
3704    typedef typename iterator_traits<_BirdirectionalIterator>::value_type value_type;
3705    if (__first != __last)
3706    {
3707        _BirdirectionalIterator __i = __first;
3708        for (++__i; __i != __last; ++__i)
3709        {
3710            _BirdirectionalIterator __j = __i;
3711            value_type __t(_VSTD::move(*__j));
3712            for (_BirdirectionalIterator __k = __i; __k != __first && __comp(__t,  *--__k); --__j)
3713                *__j = _VSTD::move(*__k);
3714            *__j = _VSTD::move(__t);
3715        }
3716    }
3717}
3718
3719template <class _Compare, class _RandomAccessIterator>
3720void
3721__insertion_sort_3(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
3722{
3723    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
3724    _RandomAccessIterator __j = __first+2;
3725    __sort3<_Compare>(__first, __first+1, __j, __comp);
3726    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
3727    {
3728        if (__comp(*__i, *__j))
3729        {
3730            value_type __t(_VSTD::move(*__i));
3731            _RandomAccessIterator __k = __j;
3732            __j = __i;
3733            do
3734            {
3735                *__j = _VSTD::move(*__k);
3736                __j = __k;
3737            } while (__j != __first && __comp(__t, *--__k));
3738            *__j = _VSTD::move(__t);
3739        }
3740        __j = __i;
3741    }
3742}
3743
3744template <class _Compare, class _RandomAccessIterator>
3745bool
3746__insertion_sort_incomplete(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
3747{
3748    switch (__last - __first)
3749    {
3750    case 0:
3751    case 1:
3752        return true;
3753    case 2:
3754        if (__comp(*--__last, *__first))
3755            swap(*__first, *__last);
3756        return true;
3757    case 3:
3758        _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
3759        return true;
3760    case 4:
3761        _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
3762        return true;
3763    case 5:
3764        _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
3765        return true;
3766    }
3767    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
3768    _RandomAccessIterator __j = __first+2;
3769    __sort3<_Compare>(__first, __first+1, __j, __comp);
3770    const unsigned __limit = 8;
3771    unsigned __count = 0;
3772    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
3773    {
3774        if (__comp(*__i, *__j))
3775        {
3776            value_type __t(_VSTD::move(*__i));
3777            _RandomAccessIterator __k = __j;
3778            __j = __i;
3779            do
3780            {
3781                *__j = _VSTD::move(*__k);
3782                __j = __k;
3783            } while (__j != __first && __comp(__t, *--__k));
3784            *__j = _VSTD::move(__t);
3785            if (++__count == __limit)
3786                return ++__i == __last;
3787        }
3788        __j = __i;
3789    }
3790    return true;
3791}
3792
3793template <class _Compare, class _BirdirectionalIterator>
3794void
3795__insertion_sort_move(_BirdirectionalIterator __first1, _BirdirectionalIterator __last1,
3796                      typename iterator_traits<_BirdirectionalIterator>::value_type* __first2, _Compare __comp)
3797{
3798    typedef typename iterator_traits<_BirdirectionalIterator>::value_type value_type;
3799    if (__first1 != __last1)
3800    {
3801        __destruct_n __d(0);
3802        unique_ptr<value_type, __destruct_n&> __h(__first2, __d);
3803        value_type* __last2 = __first2;
3804        ::new(__last2) value_type(_VSTD::move(*__first1));
3805        __d.__incr((value_type*)0);
3806        for (++__last2; ++__first1 != __last1; ++__last2)
3807        {
3808            value_type* __j2 = __last2;
3809            value_type* __i2 = __j2;
3810            if (__comp(*__first1, *--__i2))
3811            {
3812                ::new(__j2) value_type(_VSTD::move(*__i2));
3813                __d.__incr((value_type*)0);
3814                for (--__j2; __i2 != __first2 && __comp(*__first1,  *--__i2); --__j2)
3815                    *__j2 = _VSTD::move(*__i2);
3816                *__j2 = _VSTD::move(*__first1);
3817            }
3818            else
3819            {
3820                ::new(__j2) value_type(_VSTD::move(*__first1));
3821                __d.__incr((value_type*)0);
3822            }
3823        }
3824        __h.release();
3825    }
3826}
3827
3828template <class _Compare, class _RandomAccessIterator>
3829void
3830__sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
3831{
3832    // _Compare is known to be a reference type
3833    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
3834    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
3835    const difference_type __limit = is_trivially_copy_constructible<value_type>::value &&
3836                                    is_trivially_copy_assignable<value_type>::value ? 30 : 6;
3837    while (true)
3838    {
3839    __restart:
3840        difference_type __len = __last - __first;
3841        switch (__len)
3842        {
3843        case 0:
3844        case 1:
3845            return;
3846        case 2:
3847            if (__comp(*--__last, *__first))
3848                swap(*__first, *__last);
3849            return;
3850        case 3:
3851            _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
3852            return;
3853        case 4:
3854            _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
3855            return;
3856        case 5:
3857            _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
3858            return;
3859        }
3860        if (__len <= __limit)
3861        {
3862            _VSTD::__insertion_sort_3<_Compare>(__first, __last, __comp);
3863            return;
3864        }
3865        // __len > 5
3866        _RandomAccessIterator __m = __first;
3867        _RandomAccessIterator __lm1 = __last;
3868        --__lm1;
3869        unsigned __n_swaps;
3870        {
3871        difference_type __delta;
3872        if (__len >= 1000)
3873        {
3874            __delta = __len/2;
3875            __m += __delta;
3876            __delta /= 2;
3877            __n_swaps = _VSTD::__sort5<_Compare>(__first, __first + __delta, __m, __m+__delta, __lm1, __comp);
3878        }
3879        else
3880        {
3881            __delta = __len/2;
3882            __m += __delta;
3883            __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, __lm1, __comp);
3884        }
3885        }
3886        // *__m is median
3887        // partition [__first, __m) < *__m and *__m <= [__m, __last)
3888        // (this inhibits tossing elements equivalent to __m around unnecessarily)
3889        _RandomAccessIterator __i = __first;
3890        _RandomAccessIterator __j = __lm1;
3891        // j points beyond range to be tested, *__m is known to be <= *__lm1
3892        // The search going up is known to be guarded but the search coming down isn't.
3893        // Prime the downward search with a guard.
3894        if (!__comp(*__i, *__m))  // if *__first == *__m
3895        {
3896            // *__first == *__m, *__first doesn't go in first part
3897            // manually guard downward moving __j against __i
3898            while (true)
3899            {
3900                if (__i == --__j)
3901                {
3902                    // *__first == *__m, *__m <= all other elements
3903                    // Parition instead into [__first, __i) == *__first and *__first < [__i, __last)
3904                    ++__i;  // __first + 1
3905                    __j = __last;
3906                    if (!__comp(*__first, *--__j))  // we need a guard if *__first == *(__last-1)
3907                    {
3908                        while (true)
3909                        {
3910                            if (__i == __j)
3911                                return;  // [__first, __last) all equivalent elements
3912                            if (__comp(*__first, *__i))
3913                            {
3914                                swap(*__i, *__j);
3915                                ++__n_swaps;
3916                                ++__i;
3917                                break;
3918                            }
3919                            ++__i;
3920                        }
3921                    }
3922                    // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
3923                    if (__i == __j)
3924                        return;
3925                    while (true)
3926                    {
3927                        while (!__comp(*__first, *__i))
3928                            ++__i;
3929                        while (__comp(*__first, *--__j))
3930                            ;
3931                        if (__i >= __j)
3932                            break;
3933                        swap(*__i, *__j);
3934                        ++__n_swaps;
3935                        ++__i;
3936                    }
3937                    // [__first, __i) == *__first and *__first < [__i, __last)
3938                    // The first part is sorted, sort the secod part
3939                    // _VSTD::__sort<_Compare>(__i, __last, __comp);
3940                    __first = __i;
3941                    goto __restart;
3942                }
3943                if (__comp(*__j, *__m))
3944                {
3945                    swap(*__i, *__j);
3946                    ++__n_swaps;
3947                    break;  // found guard for downward moving __j, now use unguarded partition
3948                }
3949            }
3950        }
3951        // It is known that *__i < *__m
3952        ++__i;
3953        // j points beyond range to be tested, *__m is known to be <= *__lm1
3954        // if not yet partitioned...
3955        if (__i < __j)
3956        {
3957            // known that *(__i - 1) < *__m
3958            // known that __i <= __m
3959            while (true)
3960            {
3961                // __m still guards upward moving __i
3962                while (__comp(*__i, *__m))
3963                    ++__i;
3964                // It is now known that a guard exists for downward moving __j
3965                while (!__comp(*--__j, *__m))
3966                    ;
3967                if (__i > __j)
3968                    break;
3969                swap(*__i, *__j);
3970                ++__n_swaps;
3971                // It is known that __m != __j
3972                // If __m just moved, follow it
3973                if (__m == __i)
3974                    __m = __j;
3975                ++__i;
3976            }
3977        }
3978        // [__first, __i) < *__m and *__m <= [__i, __last)
3979        if (__i != __m && __comp(*__m, *__i))
3980        {
3981            swap(*__i, *__m);
3982            ++__n_swaps;
3983        }
3984        // [__first, __i) < *__i and *__i <= [__i+1, __last)
3985        // If we were given a perfect partition, see if insertion sort is quick...
3986        if (__n_swaps == 0)
3987        {
3988            bool __fs = _VSTD::__insertion_sort_incomplete<_Compare>(__first, __i, __comp);
3989            if (_VSTD::__insertion_sort_incomplete<_Compare>(__i+1, __last, __comp))
3990            {
3991                if (__fs)
3992                    return;
3993                __last = __i;
3994                continue;
3995            }
3996            else
3997            {
3998                if (__fs)
3999                {
4000                    __first = ++__i;
4001                    continue;
4002                }
4003            }
4004        }
4005        // sort smaller range with recursive call and larger with tail recursion elimination
4006        if (__i - __first < __last - __i)
4007        {
4008            _VSTD::__sort<_Compare>(__first, __i, __comp);
4009            // _VSTD::__sort<_Compare>(__i+1, __last, __comp);
4010            __first = ++__i;
4011        }
4012        else
4013        {
4014            _VSTD::__sort<_Compare>(__i+1, __last, __comp);
4015            // _VSTD::__sort<_Compare>(__first, __i, __comp);
4016            __last = __i;
4017        }
4018    }
4019}
4020
4021// This forwarder keeps the top call and the recursive calls using the same instantiation, forcing a reference _Compare
4022template <class _RandomAccessIterator, class _Compare>
4023inline _LIBCPP_INLINE_VISIBILITY
4024void
4025sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4026{
4027#ifdef _LIBCPP_DEBUG
4028    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4029    __debug_less<_Compare> __c(__comp);
4030    __sort<_Comp_ref>(__first, __last, __c);
4031#else  // _LIBCPP_DEBUG
4032    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4033    __sort<_Comp_ref>(__first, __last, __comp);
4034#endif  // _LIBCPP_DEBUG
4035}
4036
4037template <class _RandomAccessIterator>
4038inline _LIBCPP_INLINE_VISIBILITY
4039void
4040sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
4041{
4042    _VSTD::sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4043}
4044
4045template <class _Tp>
4046inline _LIBCPP_INLINE_VISIBILITY
4047void
4048sort(_Tp** __first, _Tp** __last)
4049{
4050    _VSTD::sort((size_t*)__first, (size_t*)__last, __less<size_t>());
4051}
4052
4053template <class _Tp>
4054inline _LIBCPP_INLINE_VISIBILITY
4055void
4056sort(__wrap_iter<_Tp*> __first, __wrap_iter<_Tp*> __last)
4057{
4058    _VSTD::sort(__first.base(), __last.base());
4059}
4060
4061template <class _Tp, class _Compare>
4062inline _LIBCPP_INLINE_VISIBILITY
4063void
4064sort(__wrap_iter<_Tp*> __first, __wrap_iter<_Tp*> __last, _Compare __comp)
4065{
4066    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4067    _VSTD::sort<_Tp*, _Comp_ref>(__first.base(), __last.base(), __comp);
4068}
4069
4070#ifdef _LIBCPP_MSVC
4071#pragma warning( push )
4072#pragma warning( disable: 4231)
4073#endif // _LIBCPP_MSVC
4074_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<char>&, char*>(char*, char*, __less<char>&))
4075_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
4076_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
4077_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
4078_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<short>&, short*>(short*, short*, __less<short>&))
4079_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
4080_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<int>&, int*>(int*, int*, __less<int>&))
4081_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
4082_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long>&, long*>(long*, long*, __less<long>&))
4083_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
4084_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
4085_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
4086_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<float>&, float*>(float*, float*, __less<float>&))
4087_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<double>&, double*>(double*, double*, __less<double>&))
4088_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
4089
4090_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<char>&, char*>(char*, char*, __less<char>&))
4091_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
4092_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
4093_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
4094_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<short>&, short*>(short*, short*, __less<short>&))
4095_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
4096_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<int>&, int*>(int*, int*, __less<int>&))
4097_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
4098_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long>&, long*>(long*, long*, __less<long>&))
4099_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
4100_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
4101_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
4102_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<float>&, float*>(float*, float*, __less<float>&))
4103_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<double>&, double*>(double*, double*, __less<double>&))
4104_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
4105
4106_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS unsigned __sort5<__less<long double>&, long double*>(long double*, long double*, long double*, long double*, long double*, __less<long double>&))
4107#ifdef _LIBCPP_MSVC
4108#pragma warning( pop )
4109#endif  // _LIBCPP_MSVC
4110
4111// lower_bound
4112
4113template <class _Compare, class _ForwardIterator, class _Tp>
4114_ForwardIterator
4115__lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4116{
4117    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
4118    difference_type __len = _VSTD::distance(__first, __last);
4119    while (__len != 0)
4120    {
4121        difference_type __l2 = __len / 2;
4122        _ForwardIterator __m = __first;
4123        _VSTD::advance(__m, __l2);
4124        if (__comp(*__m, __value_))
4125        {
4126            __first = ++__m;
4127            __len -= __l2 + 1;
4128        }
4129        else
4130            __len = __l2;
4131    }
4132    return __first;
4133}
4134
4135template <class _ForwardIterator, class _Tp, class _Compare>
4136inline _LIBCPP_INLINE_VISIBILITY
4137_ForwardIterator
4138lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4139{
4140#ifdef _LIBCPP_DEBUG
4141    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4142    __debug_less<_Compare> __c(__comp);
4143    return __lower_bound<_Comp_ref>(__first, __last, __value_, __c);
4144#else  // _LIBCPP_DEBUG
4145    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4146    return __lower_bound<_Comp_ref>(__first, __last, __value_, __comp);
4147#endif  // _LIBCPP_DEBUG
4148}
4149
4150template <class _ForwardIterator, class _Tp>
4151inline _LIBCPP_INLINE_VISIBILITY
4152_ForwardIterator
4153lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
4154{
4155    return _VSTD::lower_bound(__first, __last, __value_,
4156                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
4157}
4158
4159// upper_bound
4160
4161template <class _Compare, class _ForwardIterator, class _Tp>
4162_ForwardIterator
4163__upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4164{
4165    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
4166    difference_type __len = _VSTD::distance(__first, __last);
4167    while (__len != 0)
4168    {
4169        difference_type __l2 = __len / 2;
4170        _ForwardIterator __m = __first;
4171        _VSTD::advance(__m, __l2);
4172        if (__comp(__value_, *__m))
4173            __len = __l2;
4174        else
4175        {
4176            __first = ++__m;
4177            __len -= __l2 + 1;
4178        }
4179    }
4180    return __first;
4181}
4182
4183template <class _ForwardIterator, class _Tp, class _Compare>
4184inline _LIBCPP_INLINE_VISIBILITY
4185_ForwardIterator
4186upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4187{
4188#ifdef _LIBCPP_DEBUG
4189    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4190    __debug_less<_Compare> __c(__comp);
4191    return __upper_bound<_Comp_ref>(__first, __last, __value_, __c);
4192#else  // _LIBCPP_DEBUG
4193    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4194    return __upper_bound<_Comp_ref>(__first, __last, __value_, __comp);
4195#endif  // _LIBCPP_DEBUG
4196}
4197
4198template <class _ForwardIterator, class _Tp>
4199inline _LIBCPP_INLINE_VISIBILITY
4200_ForwardIterator
4201upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
4202{
4203    return _VSTD::upper_bound(__first, __last, __value_,
4204                             __less<_Tp, typename iterator_traits<_ForwardIterator>::value_type>());
4205}
4206
4207// equal_range
4208
4209template <class _Compare, class _ForwardIterator, class _Tp>
4210pair<_ForwardIterator, _ForwardIterator>
4211__equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4212{
4213    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
4214    difference_type __len = _VSTD::distance(__first, __last);
4215    while (__len != 0)
4216    {
4217        difference_type __l2 = __len / 2;
4218        _ForwardIterator __m = __first;
4219        _VSTD::advance(__m, __l2);
4220        if (__comp(*__m, __value_))
4221        {
4222            __first = ++__m;
4223            __len -= __l2 + 1;
4224        }
4225        else if (__comp(__value_, *__m))
4226        {
4227            __last = __m;
4228            __len = __l2;
4229        }
4230        else
4231        {
4232            _ForwardIterator __mp1 = __m;
4233            return pair<_ForwardIterator, _ForwardIterator>
4234                   (
4235                      __lower_bound<_Compare>(__first, __m, __value_, __comp),
4236                      __upper_bound<_Compare>(++__mp1, __last, __value_, __comp)
4237                   );
4238        }
4239    }
4240    return pair<_ForwardIterator, _ForwardIterator>(__first, __first);
4241}
4242
4243template <class _ForwardIterator, class _Tp, class _Compare>
4244inline _LIBCPP_INLINE_VISIBILITY
4245pair<_ForwardIterator, _ForwardIterator>
4246equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4247{
4248#ifdef _LIBCPP_DEBUG
4249    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4250    __debug_less<_Compare> __c(__comp);
4251    return __equal_range<_Comp_ref>(__first, __last, __value_, __c);
4252#else  // _LIBCPP_DEBUG
4253    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4254    return __equal_range<_Comp_ref>(__first, __last, __value_, __comp);
4255#endif  // _LIBCPP_DEBUG
4256}
4257
4258template <class _ForwardIterator, class _Tp>
4259inline _LIBCPP_INLINE_VISIBILITY
4260pair<_ForwardIterator, _ForwardIterator>
4261equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
4262{
4263    return _VSTD::equal_range(__first, __last, __value_,
4264                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
4265}
4266
4267// binary_search
4268
4269template <class _Compare, class _ForwardIterator, class _Tp>
4270inline _LIBCPP_INLINE_VISIBILITY
4271bool
4272__binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4273{
4274    __first = __lower_bound<_Compare>(__first, __last, __value_, __comp);
4275    return __first != __last && !__comp(__value_, *__first);
4276}
4277
4278template <class _ForwardIterator, class _Tp, class _Compare>
4279inline _LIBCPP_INLINE_VISIBILITY
4280bool
4281binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
4282{
4283#ifdef _LIBCPP_DEBUG
4284    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4285    __debug_less<_Compare> __c(__comp);
4286    return __binary_search<_Comp_ref>(__first, __last, __value_, __c);
4287#else  // _LIBCPP_DEBUG
4288    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4289    return __binary_search<_Comp_ref>(__first, __last, __value_, __comp);
4290#endif  // _LIBCPP_DEBUG
4291}
4292
4293template <class _ForwardIterator, class _Tp>
4294inline _LIBCPP_INLINE_VISIBILITY
4295bool
4296binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
4297{
4298    return _VSTD::binary_search(__first, __last, __value_,
4299                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
4300}
4301
4302// merge
4303
4304template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
4305_OutputIterator
4306__merge(_InputIterator1 __first1, _InputIterator1 __last1,
4307        _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
4308{
4309    for (; __first1 != __last1; ++__result)
4310    {
4311        if (__first2 == __last2)
4312            return _VSTD::copy(__first1, __last1, __result);
4313        if (__comp(*__first2, *__first1))
4314        {
4315            *__result = *__first2;
4316            ++__first2;
4317        }
4318        else
4319        {
4320            *__result = *__first1;
4321            ++__first1;
4322        }
4323    }
4324    return _VSTD::copy(__first2, __last2, __result);
4325}
4326
4327template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
4328inline _LIBCPP_INLINE_VISIBILITY
4329_OutputIterator
4330merge(_InputIterator1 __first1, _InputIterator1 __last1,
4331      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
4332{
4333#ifdef _LIBCPP_DEBUG
4334    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4335    __debug_less<_Compare> __c(__comp);
4336    return _VSTD::__merge<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __c);
4337#else  // _LIBCPP_DEBUG
4338    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4339    return _VSTD::__merge<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
4340#endif  // _LIBCPP_DEBUG
4341}
4342
4343template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
4344inline _LIBCPP_INLINE_VISIBILITY
4345_OutputIterator
4346merge(_InputIterator1 __first1, _InputIterator1 __last1,
4347      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
4348{
4349    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
4350    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
4351    return merge(__first1, __last1, __first2, __last2, __result, __less<__v1, __v2>());
4352}
4353
4354// inplace_merge
4355
4356template <class _Compare, class _BidirectionalIterator>
4357void
4358__buffered_inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
4359                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
4360                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
4361                typename iterator_traits<_BidirectionalIterator>::value_type* __buff)
4362{
4363    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
4364    __destruct_n __d(0);
4365    unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
4366    if (__len1 <= __len2)
4367    {
4368        value_type* __p = __buff;
4369        for (_BidirectionalIterator __i = __first; __i != __middle; __d.__incr((value_type*)0), (void) ++__i, ++__p)
4370            ::new(__p) value_type(_VSTD::move(*__i));
4371        __merge<_Compare>(move_iterator<value_type*>(__buff),
4372                          move_iterator<value_type*>(__p),
4373                          move_iterator<_BidirectionalIterator>(__middle),
4374                          move_iterator<_BidirectionalIterator>(__last),
4375                          __first, __comp);
4376    }
4377    else
4378    {
4379        value_type* __p = __buff;
4380        for (_BidirectionalIterator __i = __middle; __i != __last; __d.__incr((value_type*)0), (void) ++__i, ++__p)
4381            ::new(__p) value_type(_VSTD::move(*__i));
4382        typedef reverse_iterator<_BidirectionalIterator> _RBi;
4383        typedef reverse_iterator<value_type*> _Rv;
4384        __merge(move_iterator<_RBi>(_RBi(__middle)), move_iterator<_RBi>(_RBi(__first)),
4385                move_iterator<_Rv>(_Rv(__p)), move_iterator<_Rv>(_Rv(__buff)),
4386                _RBi(__last), __negate<_Compare>(__comp));
4387    }
4388}
4389
4390template <class _Compare, class _BidirectionalIterator>
4391void
4392__inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
4393                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
4394                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
4395                typename iterator_traits<_BidirectionalIterator>::value_type* __buff, ptrdiff_t __buff_size)
4396{
4397    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
4398    while (true)
4399    {
4400        // if __middle == __last, we're done
4401        if (__len2 == 0)
4402            return;
4403        if (__len1 <= __buff_size || __len2 <= __buff_size)
4404            return __buffered_inplace_merge<_Compare>
4405                   (__first, __middle, __last, __comp, __len1, __len2, __buff);
4406        // shrink [__first, __middle) as much as possible (with no moves), returning if it shrinks to 0
4407        for (; true; ++__first, (void) --__len1)
4408        {
4409            if (__len1 == 0)
4410                return;
4411            if (__comp(*__middle, *__first))
4412                break;
4413        }
4414        // __first < __middle < __last
4415        // *__first > *__middle
4416        // partition [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last) such that
4417        //     all elements in:
4418        //         [__first, __m1)  <= [__middle, __m2)
4419        //         [__middle, __m2) <  [__m1, __middle)
4420        //         [__m1, __middle) <= [__m2, __last)
4421        //     and __m1 or __m2 is in the middle of its range
4422        _BidirectionalIterator __m1;  // "median" of [__first, __middle)
4423        _BidirectionalIterator __m2;  // "median" of [__middle, __last)
4424        difference_type __len11;      // distance(__first, __m1)
4425        difference_type __len21;      // distance(__middle, __m2)
4426        // binary search smaller range
4427        if (__len1 < __len2)
4428        {   // __len >= 1, __len2 >= 2
4429            __len21 = __len2 / 2;
4430            __m2 = __middle;
4431            _VSTD::advance(__m2, __len21);
4432            __m1 = __upper_bound<_Compare>(__first, __middle, *__m2, __comp);
4433            __len11 = _VSTD::distance(__first, __m1);
4434        }
4435        else
4436        {
4437            if (__len1 == 1)
4438            {   // __len1 >= __len2 && __len2 > 0, therefore __len2 == 1
4439                // It is known *__first > *__middle
4440                swap(*__first, *__middle);
4441                return;
4442            }
4443            // __len1 >= 2, __len2 >= 1
4444            __len11 = __len1 / 2;
4445            __m1 = __first;
4446            _VSTD::advance(__m1, __len11);
4447            __m2 = __lower_bound<_Compare>(__middle, __last, *__m1, __comp);
4448            __len21 = _VSTD::distance(__middle, __m2);
4449        }
4450        difference_type __len12 = __len1 - __len11;  // distance(__m1, __middle)
4451        difference_type __len22 = __len2 - __len21;  // distance(__m2, __last)
4452        // [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last)
4453        // swap middle two partitions
4454        __middle = _VSTD::rotate(__m1, __middle, __m2);
4455        // __len12 and __len21 now have swapped meanings
4456        // merge smaller range with recurisve call and larger with tail recursion elimination
4457        if (__len11 + __len21 < __len12 + __len22)
4458        {
4459            __inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
4460//          __inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
4461            __first = __middle;
4462            __middle = __m2;
4463            __len1 = __len12;
4464            __len2 = __len22;
4465        }
4466        else
4467        {
4468            __inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
4469//          __inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
4470            __last = __middle;
4471            __middle = __m1;
4472            __len1 = __len11;
4473            __len2 = __len21;
4474        }
4475    }
4476}
4477
4478template <class _BidirectionalIterator, class _Compare>
4479inline _LIBCPP_INLINE_VISIBILITY
4480void
4481inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
4482              _Compare __comp)
4483{
4484    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
4485    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
4486    difference_type __len1 = _VSTD::distance(__first, __middle);
4487    difference_type __len2 = _VSTD::distance(__middle, __last);
4488    difference_type __buf_size = _VSTD::min(__len1, __len2);
4489    pair<value_type*, ptrdiff_t> __buf = _VSTD::get_temporary_buffer<value_type>(__buf_size);
4490    unique_ptr<value_type, __return_temporary_buffer> __h(__buf.first);
4491
4492#ifdef _LIBCPP_DEBUG
4493    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4494    __debug_less<_Compare> __c(__comp);
4495    return _VSTD::__inplace_merge<_Comp_ref>(__first, __middle, __last, __c, __len1, __len2,
4496                                            __buf.first, __buf.second);
4497#else  // _LIBCPP_DEBUG
4498    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4499    return _VSTD::__inplace_merge<_Comp_ref>(__first, __middle, __last, __comp, __len1, __len2,
4500                                            __buf.first, __buf.second);
4501#endif  // _LIBCPP_DEBUG
4502}
4503
4504template <class _BidirectionalIterator>
4505inline _LIBCPP_INLINE_VISIBILITY
4506void
4507inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last)
4508{
4509    _VSTD::inplace_merge(__first, __middle, __last,
4510                        __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
4511}
4512
4513// stable_sort
4514
4515template <class _Compare, class _InputIterator1, class _InputIterator2>
4516void
4517__merge_move_construct(_InputIterator1 __first1, _InputIterator1 __last1,
4518        _InputIterator2 __first2, _InputIterator2 __last2,
4519        typename iterator_traits<_InputIterator1>::value_type* __result, _Compare __comp)
4520{
4521    typedef typename iterator_traits<_InputIterator1>::value_type value_type;
4522    __destruct_n __d(0);
4523    unique_ptr<value_type, __destruct_n&> __h(__result, __d);
4524    for (; true; ++__result)
4525    {
4526        if (__first1 == __last1)
4527        {
4528            for (; __first2 != __last2; ++__first2, ++__result, __d.__incr((value_type*)0))
4529                ::new (__result) value_type(_VSTD::move(*__first2));
4530            __h.release();
4531            return;
4532        }
4533        if (__first2 == __last2)
4534        {
4535            for (; __first1 != __last1; ++__first1, ++__result, __d.__incr((value_type*)0))
4536                ::new (__result) value_type(_VSTD::move(*__first1));
4537            __h.release();
4538            return;
4539        }
4540        if (__comp(*__first2, *__first1))
4541        {
4542            ::new (__result) value_type(_VSTD::move(*__first2));
4543            __d.__incr((value_type*)0);
4544            ++__first2;
4545        }
4546        else
4547        {
4548            ::new (__result) value_type(_VSTD::move(*__first1));
4549            __d.__incr((value_type*)0);
4550            ++__first1;
4551        }
4552    }
4553}
4554
4555template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
4556void
4557__merge_move_assign(_InputIterator1 __first1, _InputIterator1 __last1,
4558        _InputIterator2 __first2, _InputIterator2 __last2,
4559        _OutputIterator __result, _Compare __comp)
4560{
4561    for (; __first1 != __last1; ++__result)
4562    {
4563        if (__first2 == __last2)
4564        {
4565            for (; __first1 != __last1; ++__first1, ++__result)
4566                *__result = _VSTD::move(*__first1);
4567            return;
4568        }
4569        if (__comp(*__first2, *__first1))
4570        {
4571            *__result = _VSTD::move(*__first2);
4572            ++__first2;
4573        }
4574        else
4575        {
4576            *__result = _VSTD::move(*__first1);
4577            ++__first1;
4578        }
4579    }
4580    for (; __first2 != __last2; ++__first2, ++__result)
4581        *__result = _VSTD::move(*__first2);
4582}
4583
4584template <class _Compare, class _RandomAccessIterator>
4585void
4586__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
4587              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
4588              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size);
4589
4590template <class _Compare, class _RandomAccessIterator>
4591void
4592__stable_sort_move(_RandomAccessIterator __first1, _RandomAccessIterator __last1, _Compare __comp,
4593                   typename iterator_traits<_RandomAccessIterator>::difference_type __len,
4594                   typename iterator_traits<_RandomAccessIterator>::value_type* __first2)
4595{
4596    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
4597    switch (__len)
4598    {
4599    case 0:
4600        return;
4601    case 1:
4602        ::new(__first2) value_type(_VSTD::move(*__first1));
4603        return;
4604    case 2:
4605       __destruct_n __d(0);
4606        unique_ptr<value_type, __destruct_n&> __h2(__first2, __d);
4607         if (__comp(*--__last1, *__first1))
4608        {
4609            ::new(__first2) value_type(_VSTD::move(*__last1));
4610            __d.__incr((value_type*)0);
4611            ++__first2;
4612            ::new(__first2) value_type(_VSTD::move(*__first1));
4613        }
4614        else
4615        {
4616            ::new(__first2) value_type(_VSTD::move(*__first1));
4617            __d.__incr((value_type*)0);
4618            ++__first2;
4619            ::new(__first2) value_type(_VSTD::move(*__last1));
4620        }
4621        __h2.release();
4622        return;
4623    }
4624    if (__len <= 8)
4625    {
4626        __insertion_sort_move<_Compare>(__first1, __last1, __first2, __comp);
4627        return;
4628    }
4629    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
4630    _RandomAccessIterator __m = __first1 + __l2;
4631    __stable_sort<_Compare>(__first1, __m, __comp, __l2, __first2, __l2);
4632    __stable_sort<_Compare>(__m, __last1, __comp, __len - __l2, __first2 + __l2, __len - __l2);
4633    __merge_move_construct<_Compare>(__first1, __m, __m, __last1, __first2, __comp);
4634}
4635
4636template <class _Tp>
4637struct __stable_sort_switch
4638{
4639    static const unsigned value = 128*is_trivially_copy_assignable<_Tp>::value;
4640};
4641
4642template <class _Compare, class _RandomAccessIterator>
4643void
4644__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
4645              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
4646              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size)
4647{
4648    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
4649    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4650    switch (__len)
4651    {
4652    case 0:
4653    case 1:
4654        return;
4655    case 2:
4656        if (__comp(*--__last, *__first))
4657            swap(*__first, *__last);
4658        return;
4659    }
4660    if (__len <= static_cast<difference_type>(__stable_sort_switch<value_type>::value))
4661    {
4662        __insertion_sort<_Compare>(__first, __last, __comp);
4663        return;
4664    }
4665    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
4666    _RandomAccessIterator __m = __first + __l2;
4667    if (__len <= __buff_size)
4668    {
4669        __destruct_n __d(0);
4670        unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
4671        __stable_sort_move<_Compare>(__first, __m, __comp, __l2, __buff);
4672        __d.__set(__l2, (value_type*)0);
4673        __stable_sort_move<_Compare>(__m, __last, __comp, __len - __l2, __buff + __l2);
4674        __d.__set(__len, (value_type*)0);
4675        __merge_move_assign<_Compare>(__buff, __buff + __l2, __buff + __l2, __buff + __len, __first, __comp);
4676//         __merge<_Compare>(move_iterator<value_type*>(__buff),
4677//                           move_iterator<value_type*>(__buff + __l2),
4678//                           move_iterator<_RandomAccessIterator>(__buff + __l2),
4679//                           move_iterator<_RandomAccessIterator>(__buff + __len),
4680//                           __first, __comp);
4681        return;
4682    }
4683    __stable_sort<_Compare>(__first, __m, __comp, __l2, __buff, __buff_size);
4684    __stable_sort<_Compare>(__m, __last, __comp, __len - __l2, __buff, __buff_size);
4685    __inplace_merge<_Compare>(__first, __m, __last, __comp, __l2, __len - __l2, __buff, __buff_size);
4686}
4687
4688template <class _RandomAccessIterator, class _Compare>
4689inline _LIBCPP_INLINE_VISIBILITY
4690void
4691stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4692{
4693    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
4694    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4695    difference_type __len = __last - __first;
4696    pair<value_type*, ptrdiff_t> __buf(0, 0);
4697    unique_ptr<value_type, __return_temporary_buffer> __h;
4698    if (__len > static_cast<difference_type>(__stable_sort_switch<value_type>::value))
4699    {
4700        __buf = _VSTD::get_temporary_buffer<value_type>(__len);
4701        __h.reset(__buf.first);
4702    }
4703#ifdef _LIBCPP_DEBUG
4704    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4705    __debug_less<_Compare> __c(__comp);
4706    __stable_sort<_Comp_ref>(__first, __last, __c, __len, __buf.first, __buf.second);
4707#else  // _LIBCPP_DEBUG
4708    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4709    __stable_sort<_Comp_ref>(__first, __last, __comp, __len, __buf.first, __buf.second);
4710#endif  // _LIBCPP_DEBUG
4711}
4712
4713template <class _RandomAccessIterator>
4714inline _LIBCPP_INLINE_VISIBILITY
4715void
4716stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
4717{
4718    _VSTD::stable_sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4719}
4720
4721// is_heap_until
4722
4723template <class _RandomAccessIterator, class _Compare>
4724_RandomAccessIterator
4725is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4726{
4727    typedef typename _VSTD::iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4728    difference_type __len = __last - __first;
4729    difference_type __p = 0;
4730    difference_type __c = 1;
4731    _RandomAccessIterator __pp = __first;
4732    while (__c < __len)
4733    {
4734        _RandomAccessIterator __cp = __first + __c;
4735        if (__comp(*__pp, *__cp))
4736            return __cp;
4737        ++__c;
4738        ++__cp;
4739        if (__c == __len)
4740            return __last;
4741        if (__comp(*__pp, *__cp))
4742            return __cp;
4743        ++__p;
4744        ++__pp;
4745        __c = 2 * __p + 1;
4746    }
4747    return __last;
4748}
4749
4750template<class _RandomAccessIterator>
4751inline _LIBCPP_INLINE_VISIBILITY
4752_RandomAccessIterator
4753is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last)
4754{
4755    return _VSTD::is_heap_until(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4756}
4757
4758// is_heap
4759
4760template <class _RandomAccessIterator, class _Compare>
4761inline _LIBCPP_INLINE_VISIBILITY
4762bool
4763is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4764{
4765    return _VSTD::is_heap_until(__first, __last, __comp) == __last;
4766}
4767
4768template<class _RandomAccessIterator>
4769inline _LIBCPP_INLINE_VISIBILITY
4770bool
4771is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
4772{
4773    return _VSTD::is_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4774}
4775
4776// push_heap
4777
4778template <class _Compare, class _RandomAccessIterator>
4779void
4780__sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
4781          typename iterator_traits<_RandomAccessIterator>::difference_type __len)
4782{
4783    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
4784    if (__len > 1)
4785    {
4786        __len = (__len - 2) / 2;
4787        _RandomAccessIterator __ptr = __first + __len;
4788        if (__comp(*__ptr, *--__last))
4789        {
4790            value_type __t(_VSTD::move(*__last));
4791            do
4792            {
4793                *__last = _VSTD::move(*__ptr);
4794                __last = __ptr;
4795                if (__len == 0)
4796                    break;
4797                __len = (__len - 1) / 2;
4798                __ptr = __first + __len;
4799            } while (__comp(*__ptr, __t));
4800            *__last = _VSTD::move(__t);
4801        }
4802    }
4803}
4804
4805template <class _RandomAccessIterator, class _Compare>
4806inline _LIBCPP_INLINE_VISIBILITY
4807void
4808push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4809{
4810#ifdef _LIBCPP_DEBUG
4811    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4812    __debug_less<_Compare> __c(__comp);
4813    __sift_up<_Comp_ref>(__first, __last, __c, __last - __first);
4814#else  // _LIBCPP_DEBUG
4815    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4816    __sift_up<_Comp_ref>(__first, __last, __comp, __last - __first);
4817#endif  // _LIBCPP_DEBUG
4818}
4819
4820template <class _RandomAccessIterator>
4821inline _LIBCPP_INLINE_VISIBILITY
4822void
4823push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
4824{
4825    _VSTD::push_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4826}
4827
4828// pop_heap
4829
4830template <class _Compare, class _RandomAccessIterator>
4831void
4832__sift_down(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
4833            typename iterator_traits<_RandomAccessIterator>::difference_type __len,
4834            _RandomAccessIterator __start)
4835{
4836    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4837    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
4838    // left-child of __start is at 2 * __start + 1
4839    // right-child of __start is at 2 * __start + 2
4840    difference_type __child = __start - __first;
4841
4842    if (__len < 2 || (__len - 2) / 2 < __child)
4843        return;
4844
4845    __child = 2 * __child + 1;
4846    _RandomAccessIterator __child_i = __first + __child;
4847
4848    if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
4849        // right-child exists and is greater than left-child
4850        ++__child_i;
4851        ++__child;
4852    }
4853
4854    // check if we are in heap-order
4855    if (__comp(*__child_i, *__start))
4856        // we are, __start is larger than it's largest child
4857        return;
4858
4859    value_type __top(_VSTD::move(*__start));
4860    do
4861    {
4862        // we are not in heap-order, swap the parent with it's largest child
4863        *__start = _VSTD::move(*__child_i);
4864        __start = __child_i;
4865
4866        if ((__len - 2) / 2 < __child)
4867            break;
4868
4869        // recompute the child based off of the updated parent
4870        __child = 2 * __child + 1;
4871        __child_i = __first + __child;
4872
4873        if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
4874            // right-child exists and is greater than left-child
4875            ++__child_i;
4876            ++__child;
4877        }
4878
4879        // check if we are in heap-order
4880    } while (!__comp(*__child_i, __top));
4881    *__start = _VSTD::move(__top);
4882}
4883
4884template <class _Compare, class _RandomAccessIterator>
4885inline _LIBCPP_INLINE_VISIBILITY
4886void
4887__pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
4888           typename iterator_traits<_RandomAccessIterator>::difference_type __len)
4889{
4890    if (__len > 1)
4891    {
4892        swap(*__first, *--__last);
4893        __sift_down<_Compare>(__first, __last, __comp, __len - 1, __first);
4894    }
4895}
4896
4897template <class _RandomAccessIterator, class _Compare>
4898inline _LIBCPP_INLINE_VISIBILITY
4899void
4900pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4901{
4902#ifdef _LIBCPP_DEBUG
4903    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4904    __debug_less<_Compare> __c(__comp);
4905    __pop_heap<_Comp_ref>(__first, __last, __c, __last - __first);
4906#else  // _LIBCPP_DEBUG
4907    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4908    __pop_heap<_Comp_ref>(__first, __last, __comp, __last - __first);
4909#endif  // _LIBCPP_DEBUG
4910}
4911
4912template <class _RandomAccessIterator>
4913inline _LIBCPP_INLINE_VISIBILITY
4914void
4915pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
4916{
4917    _VSTD::pop_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4918}
4919
4920// make_heap
4921
4922template <class _Compare, class _RandomAccessIterator>
4923void
4924__make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4925{
4926    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4927    difference_type __n = __last - __first;
4928    if (__n > 1)
4929    {
4930        // start from the first parent, there is no need to consider children
4931        for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start)
4932        {
4933            __sift_down<_Compare>(__first, __last, __comp, __n, __first + __start);
4934        }
4935    }
4936}
4937
4938template <class _RandomAccessIterator, class _Compare>
4939inline _LIBCPP_INLINE_VISIBILITY
4940void
4941make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4942{
4943#ifdef _LIBCPP_DEBUG
4944    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4945    __debug_less<_Compare> __c(__comp);
4946    __make_heap<_Comp_ref>(__first, __last, __c);
4947#else  // _LIBCPP_DEBUG
4948    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4949    __make_heap<_Comp_ref>(__first, __last, __comp);
4950#endif  // _LIBCPP_DEBUG
4951}
4952
4953template <class _RandomAccessIterator>
4954inline _LIBCPP_INLINE_VISIBILITY
4955void
4956make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
4957{
4958    _VSTD::make_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4959}
4960
4961// sort_heap
4962
4963template <class _Compare, class _RandomAccessIterator>
4964void
4965__sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4966{
4967    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
4968    for (difference_type __n = __last - __first; __n > 1; --__last, --__n)
4969        __pop_heap<_Compare>(__first, __last, __comp, __n);
4970}
4971
4972template <class _RandomAccessIterator, class _Compare>
4973inline _LIBCPP_INLINE_VISIBILITY
4974void
4975sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
4976{
4977#ifdef _LIBCPP_DEBUG
4978    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
4979    __debug_less<_Compare> __c(__comp);
4980    __sort_heap<_Comp_ref>(__first, __last, __c);
4981#else  // _LIBCPP_DEBUG
4982    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
4983    __sort_heap<_Comp_ref>(__first, __last, __comp);
4984#endif  // _LIBCPP_DEBUG
4985}
4986
4987template <class _RandomAccessIterator>
4988inline _LIBCPP_INLINE_VISIBILITY
4989void
4990sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
4991{
4992    _VSTD::sort_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
4993}
4994
4995// partial_sort
4996
4997template <class _Compare, class _RandomAccessIterator>
4998void
4999__partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
5000             _Compare __comp)
5001{
5002    __make_heap<_Compare>(__first, __middle, __comp);
5003    typename iterator_traits<_RandomAccessIterator>::difference_type __len = __middle - __first;
5004    for (_RandomAccessIterator __i = __middle; __i != __last; ++__i)
5005    {
5006        if (__comp(*__i, *__first))
5007        {
5008            swap(*__i, *__first);
5009            __sift_down<_Compare>(__first, __middle, __comp, __len, __first);
5010        }
5011    }
5012    __sort_heap<_Compare>(__first, __middle, __comp);
5013}
5014
5015template <class _RandomAccessIterator, class _Compare>
5016inline _LIBCPP_INLINE_VISIBILITY
5017void
5018partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
5019             _Compare __comp)
5020{
5021#ifdef _LIBCPP_DEBUG
5022    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5023    __debug_less<_Compare> __c(__comp);
5024    __partial_sort<_Comp_ref>(__first, __middle, __last, __c);
5025#else  // _LIBCPP_DEBUG
5026    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5027    __partial_sort<_Comp_ref>(__first, __middle, __last, __comp);
5028#endif  // _LIBCPP_DEBUG
5029}
5030
5031template <class _RandomAccessIterator>
5032inline _LIBCPP_INLINE_VISIBILITY
5033void
5034partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
5035{
5036    _VSTD::partial_sort(__first, __middle, __last,
5037                       __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
5038}
5039
5040// partial_sort_copy
5041
5042template <class _Compare, class _InputIterator, class _RandomAccessIterator>
5043_RandomAccessIterator
5044__partial_sort_copy(_InputIterator __first, _InputIterator __last,
5045                    _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
5046{
5047    _RandomAccessIterator __r = __result_first;
5048    if (__r != __result_last)
5049    {
5050        for (; __first != __last && __r != __result_last; (void) ++__first, ++__r)
5051            *__r = *__first;
5052        __make_heap<_Compare>(__result_first, __r, __comp);
5053        typename iterator_traits<_RandomAccessIterator>::difference_type __len = __r - __result_first;
5054        for (; __first != __last; ++__first)
5055            if (__comp(*__first, *__result_first))
5056            {
5057                *__result_first = *__first;
5058                __sift_down<_Compare>(__result_first, __r, __comp, __len, __result_first);
5059            }
5060        __sort_heap<_Compare>(__result_first, __r, __comp);
5061    }
5062    return __r;
5063}
5064
5065template <class _InputIterator, class _RandomAccessIterator, class _Compare>
5066inline _LIBCPP_INLINE_VISIBILITY
5067_RandomAccessIterator
5068partial_sort_copy(_InputIterator __first, _InputIterator __last,
5069                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
5070{
5071#ifdef _LIBCPP_DEBUG
5072    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5073    __debug_less<_Compare> __c(__comp);
5074    return __partial_sort_copy<_Comp_ref>(__first, __last, __result_first, __result_last, __c);
5075#else  // _LIBCPP_DEBUG
5076    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5077    return __partial_sort_copy<_Comp_ref>(__first, __last, __result_first, __result_last, __comp);
5078#endif  // _LIBCPP_DEBUG
5079}
5080
5081template <class _InputIterator, class _RandomAccessIterator>
5082inline _LIBCPP_INLINE_VISIBILITY
5083_RandomAccessIterator
5084partial_sort_copy(_InputIterator __first, _InputIterator __last,
5085                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last)
5086{
5087    return _VSTD::partial_sort_copy(__first, __last, __result_first, __result_last,
5088                                   __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
5089}
5090
5091// nth_element
5092
5093template <class _Compare, class _RandomAccessIterator>
5094void
5095__nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
5096{
5097    // _Compare is known to be a reference type
5098    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
5099    const difference_type __limit = 7;
5100    while (true)
5101    {
5102    __restart:
5103        if (__nth == __last)
5104            return;
5105        difference_type __len = __last - __first;
5106        switch (__len)
5107        {
5108        case 0:
5109        case 1:
5110            return;
5111        case 2:
5112            if (__comp(*--__last, *__first))
5113                swap(*__first, *__last);
5114            return;
5115        case 3:
5116            {
5117            _RandomAccessIterator __m = __first;
5118            _VSTD::__sort3<_Compare>(__first, ++__m, --__last, __comp);
5119            return;
5120            }
5121        }
5122        if (__len <= __limit)
5123        {
5124            __selection_sort<_Compare>(__first, __last, __comp);
5125            return;
5126        }
5127        // __len > __limit >= 3
5128        _RandomAccessIterator __m = __first + __len/2;
5129        _RandomAccessIterator __lm1 = __last;
5130        unsigned __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, --__lm1, __comp);
5131        // *__m is median
5132        // partition [__first, __m) < *__m and *__m <= [__m, __last)
5133        // (this inhibits tossing elements equivalent to __m around unnecessarily)
5134        _RandomAccessIterator __i = __first;
5135        _RandomAccessIterator __j = __lm1;
5136        // j points beyond range to be tested, *__lm1 is known to be <= *__m
5137        // The search going up is known to be guarded but the search coming down isn't.
5138        // Prime the downward search with a guard.
5139        if (!__comp(*__i, *__m))  // if *__first == *__m
5140        {
5141            // *__first == *__m, *__first doesn't go in first part
5142            // manually guard downward moving __j against __i
5143            while (true)
5144            {
5145                if (__i == --__j)
5146                {
5147                    // *__first == *__m, *__m <= all other elements
5148                    // Parition instead into [__first, __i) == *__first and *__first < [__i, __last)
5149                    ++__i;  // __first + 1
5150                    __j = __last;
5151                    if (!__comp(*__first, *--__j))  // we need a guard if *__first == *(__last-1)
5152                    {
5153                        while (true)
5154                        {
5155                            if (__i == __j)
5156                                return;  // [__first, __last) all equivalent elements
5157                            if (__comp(*__first, *__i))
5158                            {
5159                                swap(*__i, *__j);
5160                                ++__n_swaps;
5161                                ++__i;
5162                                break;
5163                            }
5164                            ++__i;
5165                        }
5166                    }
5167                    // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
5168                    if (__i == __j)
5169                        return;
5170                    while (true)
5171                    {
5172                        while (!__comp(*__first, *__i))
5173                            ++__i;
5174                        while (__comp(*__first, *--__j))
5175                            ;
5176                        if (__i >= __j)
5177                            break;
5178                        swap(*__i, *__j);
5179                        ++__n_swaps;
5180                        ++__i;
5181                    }
5182                    // [__first, __i) == *__first and *__first < [__i, __last)
5183                    // The first part is sorted,
5184                    if (__nth < __i)
5185                        return;
5186                    // __nth_element the secod part
5187                    // __nth_element<_Compare>(__i, __nth, __last, __comp);
5188                    __first = __i;
5189                    goto __restart;
5190                }
5191                if (__comp(*__j, *__m))
5192                {
5193                    swap(*__i, *__j);
5194                    ++__n_swaps;
5195                    break;  // found guard for downward moving __j, now use unguarded partition
5196                }
5197            }
5198        }
5199        ++__i;
5200        // j points beyond range to be tested, *__lm1 is known to be <= *__m
5201        // if not yet partitioned...
5202        if (__i < __j)
5203        {
5204            // known that *(__i - 1) < *__m
5205            while (true)
5206            {
5207                // __m still guards upward moving __i
5208                while (__comp(*__i, *__m))
5209                    ++__i;
5210                // It is now known that a guard exists for downward moving __j
5211                while (!__comp(*--__j, *__m))
5212                    ;
5213                if (__i >= __j)
5214                    break;
5215                swap(*__i, *__j);
5216                ++__n_swaps;
5217                // It is known that __m != __j
5218                // If __m just moved, follow it
5219                if (__m == __i)
5220                    __m = __j;
5221                ++__i;
5222            }
5223        }
5224        // [__first, __i) < *__m and *__m <= [__i, __last)
5225        if (__i != __m && __comp(*__m, *__i))
5226        {
5227            swap(*__i, *__m);
5228            ++__n_swaps;
5229        }
5230        // [__first, __i) < *__i and *__i <= [__i+1, __last)
5231        if (__nth == __i)
5232            return;
5233        if (__n_swaps == 0)
5234        {
5235            // We were given a perfectly partitioned sequence.  Coincidence?
5236            if (__nth < __i)
5237            {
5238                // Check for [__first, __i) already sorted
5239                __j = __m = __first;
5240                while (++__j != __i)
5241                {
5242                    if (__comp(*__j, *__m))
5243                        // not yet sorted, so sort
5244                        goto not_sorted;
5245                    __m = __j;
5246                }
5247                // [__first, __i) sorted
5248                return;
5249            }
5250            else
5251            {
5252                // Check for [__i, __last) already sorted
5253                __j = __m = __i;
5254                while (++__j != __last)
5255                {
5256                    if (__comp(*__j, *__m))
5257                        // not yet sorted, so sort
5258                        goto not_sorted;
5259                    __m = __j;
5260                }
5261                // [__i, __last) sorted
5262                return;
5263            }
5264        }
5265not_sorted:
5266        // __nth_element on range containing __nth
5267        if (__nth < __i)
5268        {
5269            // __nth_element<_Compare>(__first, __nth, __i, __comp);
5270            __last = __i;
5271        }
5272        else
5273        {
5274            // __nth_element<_Compare>(__i+1, __nth, __last, __comp);
5275            __first = ++__i;
5276        }
5277    }
5278}
5279
5280template <class _RandomAccessIterator, class _Compare>
5281inline _LIBCPP_INLINE_VISIBILITY
5282void
5283nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
5284{
5285#ifdef _LIBCPP_DEBUG
5286    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5287    __debug_less<_Compare> __c(__comp);
5288    __nth_element<_Comp_ref>(__first, __nth, __last, __c);
5289#else  // _LIBCPP_DEBUG
5290    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5291    __nth_element<_Comp_ref>(__first, __nth, __last, __comp);
5292#endif  // _LIBCPP_DEBUG
5293}
5294
5295template <class _RandomAccessIterator>
5296inline _LIBCPP_INLINE_VISIBILITY
5297void
5298nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last)
5299{
5300    _VSTD::nth_element(__first, __nth, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
5301}
5302
5303// includes
5304
5305template <class _Compare, class _InputIterator1, class _InputIterator2>
5306bool
5307__includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
5308           _Compare __comp)
5309{
5310    for (; __first2 != __last2; ++__first1)
5311    {
5312        if (__first1 == __last1 || __comp(*__first2, *__first1))
5313            return false;
5314        if (!__comp(*__first1, *__first2))
5315            ++__first2;
5316    }
5317    return true;
5318}
5319
5320template <class _InputIterator1, class _InputIterator2, class _Compare>
5321inline _LIBCPP_INLINE_VISIBILITY
5322bool
5323includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
5324         _Compare __comp)
5325{
5326#ifdef _LIBCPP_DEBUG
5327    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5328    __debug_less<_Compare> __c(__comp);
5329    return __includes<_Comp_ref>(__first1, __last1, __first2, __last2, __c);
5330#else  // _LIBCPP_DEBUG
5331    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5332    return __includes<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
5333#endif  // _LIBCPP_DEBUG
5334}
5335
5336template <class _InputIterator1, class _InputIterator2>
5337inline _LIBCPP_INLINE_VISIBILITY
5338bool
5339includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2)
5340{
5341    return _VSTD::includes(__first1, __last1, __first2, __last2,
5342                          __less<typename iterator_traits<_InputIterator1>::value_type,
5343                                 typename iterator_traits<_InputIterator2>::value_type>());
5344}
5345
5346// set_union
5347
5348template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
5349_OutputIterator
5350__set_union(_InputIterator1 __first1, _InputIterator1 __last1,
5351            _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5352{
5353    for (; __first1 != __last1; ++__result)
5354    {
5355        if (__first2 == __last2)
5356            return _VSTD::copy(__first1, __last1, __result);
5357        if (__comp(*__first2, *__first1))
5358        {
5359            *__result = *__first2;
5360            ++__first2;
5361        }
5362        else
5363        {
5364            *__result = *__first1;
5365            if (!__comp(*__first1, *__first2))
5366                ++__first2;
5367            ++__first1;
5368        }
5369    }
5370    return _VSTD::copy(__first2, __last2, __result);
5371}
5372
5373template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
5374inline _LIBCPP_INLINE_VISIBILITY
5375_OutputIterator
5376set_union(_InputIterator1 __first1, _InputIterator1 __last1,
5377          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5378{
5379#ifdef _LIBCPP_DEBUG
5380    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5381    __debug_less<_Compare> __c(__comp);
5382    return __set_union<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __c);
5383#else  // _LIBCPP_DEBUG
5384    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5385    return __set_union<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
5386#endif  // _LIBCPP_DEBUG
5387}
5388
5389template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
5390inline _LIBCPP_INLINE_VISIBILITY
5391_OutputIterator
5392set_union(_InputIterator1 __first1, _InputIterator1 __last1,
5393          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
5394{
5395    return _VSTD::set_union(__first1, __last1, __first2, __last2, __result,
5396                          __less<typename iterator_traits<_InputIterator1>::value_type,
5397                                 typename iterator_traits<_InputIterator2>::value_type>());
5398}
5399
5400// set_intersection
5401
5402template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
5403_OutputIterator
5404__set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
5405                   _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5406{
5407    while (__first1 != __last1 && __first2 != __last2)
5408    {
5409        if (__comp(*__first1, *__first2))
5410            ++__first1;
5411        else
5412        {
5413            if (!__comp(*__first2, *__first1))
5414            {
5415                *__result = *__first1;
5416                ++__result;
5417                ++__first1;
5418            }
5419            ++__first2;
5420        }
5421    }
5422    return __result;
5423}
5424
5425template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
5426inline _LIBCPP_INLINE_VISIBILITY
5427_OutputIterator
5428set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
5429                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5430{
5431#ifdef _LIBCPP_DEBUG
5432    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5433    __debug_less<_Compare> __c(__comp);
5434    return __set_intersection<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __c);
5435#else  // _LIBCPP_DEBUG
5436    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5437    return __set_intersection<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
5438#endif  // _LIBCPP_DEBUG
5439}
5440
5441template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
5442inline _LIBCPP_INLINE_VISIBILITY
5443_OutputIterator
5444set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
5445                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
5446{
5447    return _VSTD::set_intersection(__first1, __last1, __first2, __last2, __result,
5448                                  __less<typename iterator_traits<_InputIterator1>::value_type,
5449                                         typename iterator_traits<_InputIterator2>::value_type>());
5450}
5451
5452// set_difference
5453
5454template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
5455_OutputIterator
5456__set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5457                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5458{
5459    while (__first1 != __last1)
5460    {
5461        if (__first2 == __last2)
5462            return _VSTD::copy(__first1, __last1, __result);
5463        if (__comp(*__first1, *__first2))
5464        {
5465            *__result = *__first1;
5466            ++__result;
5467            ++__first1;
5468        }
5469        else
5470        {
5471            if (!__comp(*__first2, *__first1))
5472                ++__first1;
5473            ++__first2;
5474        }
5475    }
5476    return __result;
5477}
5478
5479template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
5480inline _LIBCPP_INLINE_VISIBILITY
5481_OutputIterator
5482set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5483               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5484{
5485#ifdef _LIBCPP_DEBUG
5486    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5487    __debug_less<_Compare> __c(__comp);
5488    return __set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __c);
5489#else  // _LIBCPP_DEBUG
5490    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5491    return __set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
5492#endif  // _LIBCPP_DEBUG
5493}
5494
5495template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
5496inline _LIBCPP_INLINE_VISIBILITY
5497_OutputIterator
5498set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5499               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
5500{
5501    return _VSTD::set_difference(__first1, __last1, __first2, __last2, __result,
5502                                __less<typename iterator_traits<_InputIterator1>::value_type,
5503                                       typename iterator_traits<_InputIterator2>::value_type>());
5504}
5505
5506// set_symmetric_difference
5507
5508template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
5509_OutputIterator
5510__set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5511                           _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5512{
5513    while (__first1 != __last1)
5514    {
5515        if (__first2 == __last2)
5516            return _VSTD::copy(__first1, __last1, __result);
5517        if (__comp(*__first1, *__first2))
5518        {
5519            *__result = *__first1;
5520            ++__result;
5521            ++__first1;
5522        }
5523        else
5524        {
5525            if (__comp(*__first2, *__first1))
5526            {
5527                *__result = *__first2;
5528                ++__result;
5529            }
5530            else
5531                ++__first1;
5532            ++__first2;
5533        }
5534    }
5535    return _VSTD::copy(__first2, __last2, __result);
5536}
5537
5538template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
5539inline _LIBCPP_INLINE_VISIBILITY
5540_OutputIterator
5541set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5542                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
5543{
5544#ifdef _LIBCPP_DEBUG
5545    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5546    __debug_less<_Compare> __c(__comp);
5547    return __set_symmetric_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __c);
5548#else  // _LIBCPP_DEBUG
5549    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5550    return __set_symmetric_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
5551#endif  // _LIBCPP_DEBUG
5552}
5553
5554template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
5555inline _LIBCPP_INLINE_VISIBILITY
5556_OutputIterator
5557set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
5558                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
5559{
5560    return _VSTD::set_symmetric_difference(__first1, __last1, __first2, __last2, __result,
5561                                          __less<typename iterator_traits<_InputIterator1>::value_type,
5562                                                 typename iterator_traits<_InputIterator2>::value_type>());
5563}
5564
5565// lexicographical_compare
5566
5567template <class _Compare, class _InputIterator1, class _InputIterator2>
5568bool
5569__lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
5570                          _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
5571{
5572    for (; __first2 != __last2; ++__first1, (void) ++__first2)
5573    {
5574        if (__first1 == __last1 || __comp(*__first1, *__first2))
5575            return true;
5576        if (__comp(*__first2, *__first1))
5577            return false;
5578    }
5579    return false;
5580}
5581
5582template <class _InputIterator1, class _InputIterator2, class _Compare>
5583inline _LIBCPP_INLINE_VISIBILITY
5584bool
5585lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
5586                        _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
5587{
5588#ifdef _LIBCPP_DEBUG
5589    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5590    __debug_less<_Compare> __c(__comp);
5591    return __lexicographical_compare<_Comp_ref>(__first1, __last1, __first2, __last2, __c);
5592#else  // _LIBCPP_DEBUG
5593    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5594    return __lexicographical_compare<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
5595#endif  // _LIBCPP_DEBUG
5596}
5597
5598template <class _InputIterator1, class _InputIterator2>
5599inline _LIBCPP_INLINE_VISIBILITY
5600bool
5601lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
5602                        _InputIterator2 __first2, _InputIterator2 __last2)
5603{
5604    return _VSTD::lexicographical_compare(__first1, __last1, __first2, __last2,
5605                                         __less<typename iterator_traits<_InputIterator1>::value_type,
5606                                                typename iterator_traits<_InputIterator2>::value_type>());
5607}
5608
5609// next_permutation
5610
5611template <class _Compare, class _BidirectionalIterator>
5612bool
5613__next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
5614{
5615    _BidirectionalIterator __i = __last;
5616    if (__first == __last || __first == --__i)
5617        return false;
5618    while (true)
5619    {
5620        _BidirectionalIterator __ip1 = __i;
5621        if (__comp(*--__i, *__ip1))
5622        {
5623            _BidirectionalIterator __j = __last;
5624            while (!__comp(*__i, *--__j))
5625                ;
5626            swap(*__i, *__j);
5627            _VSTD::reverse(__ip1, __last);
5628            return true;
5629        }
5630        if (__i == __first)
5631        {
5632            _VSTD::reverse(__first, __last);
5633            return false;
5634        }
5635    }
5636}
5637
5638template <class _BidirectionalIterator, class _Compare>
5639inline _LIBCPP_INLINE_VISIBILITY
5640bool
5641next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
5642{
5643#ifdef _LIBCPP_DEBUG
5644    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5645    __debug_less<_Compare> __c(__comp);
5646    return __next_permutation<_Comp_ref>(__first, __last, __c);
5647#else  // _LIBCPP_DEBUG
5648    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5649    return __next_permutation<_Comp_ref>(__first, __last, __comp);
5650#endif  // _LIBCPP_DEBUG
5651}
5652
5653template <class _BidirectionalIterator>
5654inline _LIBCPP_INLINE_VISIBILITY
5655bool
5656next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
5657{
5658    return _VSTD::next_permutation(__first, __last,
5659                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
5660}
5661
5662// prev_permutation
5663
5664template <class _Compare, class _BidirectionalIterator>
5665bool
5666__prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
5667{
5668    _BidirectionalIterator __i = __last;
5669    if (__first == __last || __first == --__i)
5670        return false;
5671    while (true)
5672    {
5673        _BidirectionalIterator __ip1 = __i;
5674        if (__comp(*__ip1, *--__i))
5675        {
5676            _BidirectionalIterator __j = __last;
5677            while (!__comp(*--__j, *__i))
5678                ;
5679            swap(*__i, *__j);
5680            _VSTD::reverse(__ip1, __last);
5681            return true;
5682        }
5683        if (__i == __first)
5684        {
5685            _VSTD::reverse(__first, __last);
5686            return false;
5687        }
5688    }
5689}
5690
5691template <class _BidirectionalIterator, class _Compare>
5692inline _LIBCPP_INLINE_VISIBILITY
5693bool
5694prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
5695{
5696#ifdef _LIBCPP_DEBUG
5697    typedef typename add_lvalue_reference<__debug_less<_Compare> >::type _Comp_ref;
5698    __debug_less<_Compare> __c(__comp);
5699    return __prev_permutation<_Comp_ref>(__first, __last, __c);
5700#else  // _LIBCPP_DEBUG
5701    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
5702    return __prev_permutation<_Comp_ref>(__first, __last, __comp);
5703#endif  // _LIBCPP_DEBUG
5704}
5705
5706template <class _BidirectionalIterator>
5707inline _LIBCPP_INLINE_VISIBILITY
5708bool
5709prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
5710{
5711    return _VSTD::prev_permutation(__first, __last,
5712                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
5713}
5714
5715template <class _Tp>
5716inline _LIBCPP_INLINE_VISIBILITY
5717typename enable_if
5718<
5719    is_integral<_Tp>::value,
5720    _Tp
5721>::type
5722__rotate_left(_Tp __t, _Tp __n = 1)
5723{
5724    const unsigned __bits = static_cast<unsigned>(sizeof(_Tp) * __CHAR_BIT__ - 1);
5725    __n &= __bits;
5726    return static_cast<_Tp>((__t << __n) | (static_cast<typename make_unsigned<_Tp>::type>(__t) >> (__bits - __n)));
5727}
5728
5729template <class _Tp>
5730inline _LIBCPP_INLINE_VISIBILITY
5731typename enable_if
5732<
5733    is_integral<_Tp>::value,
5734    _Tp
5735>::type
5736__rotate_right(_Tp __t, _Tp __n = 1)
5737{
5738    const unsigned __bits = static_cast<unsigned>(sizeof(_Tp) * __CHAR_BIT__ - 1);
5739    __n &= __bits;
5740    return static_cast<_Tp>((__t << (__bits - __n)) | (static_cast<typename make_unsigned<_Tp>::type>(__t) >> __n));
5741}
5742
5743_LIBCPP_END_NAMESPACE_STD
5744
5745#endif  // _LIBCPP_ALGORITHM
5746