| 1 | // Copyright (C) 2020-2025 Free Software Foundation, Inc. |
| 2 | // |
| 3 | // This file is part of the GNU ISO C++ Library. This library is free |
| 4 | // software; you can redistribute it and/or modify it under the |
| 5 | // terms of the GNU General Public License as published by the |
| 6 | // Free Software Foundation; either version 3, or (at your option) |
| 7 | // any later version. |
| 8 | |
| 9 | // This library is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU General Public License for more details. |
| 13 | |
| 14 | // You should have received a copy of the GNU General Public License along |
| 15 | // with this library; see the file COPYING3. If not see |
| 16 | // <http://www.gnu.org/licenses/>. |
| 17 | |
| 18 | // { dg-do run { target c++20 } } |
| 19 | |
| 20 | #include <algorithm> |
| 21 | #include <testsuite_hooks.h> |
| 22 | #include <testsuite_iterators.h> |
| 23 | |
| 24 | using __gnu_test::test_container; |
| 25 | using __gnu_test::test_range; |
| 26 | using __gnu_test::bidirectional_iterator_wrapper; |
| 27 | |
| 28 | namespace ranges = std::ranges; |
| 29 | |
| 30 | void |
| 31 | test01() |
| 32 | { |
| 33 | int x[] = {5, 4, 3, 2, 1}; |
| 34 | int y[] = {5, 4, 3, 2, 1}; |
| 35 | |
| 36 | for (int i = 0; i <= 5; i++) |
| 37 | { |
| 38 | test_container<int, bidirectional_iterator_wrapper> cx(x, x+i); |
| 39 | test_container<int, bidirectional_iterator_wrapper> cy(y, y+i); |
| 40 | for (int j = 0; ; j++) |
| 41 | { |
| 42 | auto found1 = std::prev_permutation(cx.begin(), cx.end()); |
| 43 | auto [last,found2] = ranges::prev_permutation(cy.begin(), cy.end()); |
| 44 | VERIFY( found1 == found2 ); |
| 45 | VERIFY( ranges::equal(cx, cy) ); |
| 46 | if (!found2) |
| 47 | break; |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | void |
| 53 | test02() |
| 54 | { |
| 55 | int x[] = {1, 2, 3, 4, 5}; |
| 56 | test_range<int, bidirectional_iterator_wrapper> rx(x); |
| 57 | auto [last,found] = ranges::prev_permutation(rx, ranges::greater{}); |
| 58 | VERIFY( found && last == rx.end() ); |
| 59 | VERIFY( last == rx.end() ); |
| 60 | VERIFY( ranges::equal(rx, (int[]){1,2,3,5,4}) ); |
| 61 | ranges::prev_permutation(rx, {}, [] (int a) { return -a; }); |
| 62 | VERIFY( ranges::equal(rx, (int[]){1,2,4,3,5}) ); |
| 63 | |
| 64 | VERIFY( !ranges::prev_permutation(x, x).found ); |
| 65 | VERIFY( !ranges::prev_permutation(x, x+1).found ); |
| 66 | } |
| 67 | |
| 68 | constexpr bool |
| 69 | test03() |
| 70 | { |
| 71 | int x[] = {3,2,1}; |
| 72 | ranges::prev_permutation(x); |
| 73 | return ranges::equal(x, (int[]){3,1,2}); |
| 74 | } |
| 75 | |
| 76 | int |
| 77 | main() |
| 78 | { |
| 79 | test01(); |
| 80 | test02(); |
| 81 | static_assert(test03()); |
| 82 | } |
| 83 |