std::ranges::next_permutation, std::ranges::next_permutation_result
Min standard notice:
Header: <algorithm>
- Transforms the range [first,last) into the next permutation, where the set of all permutations is ordered lexicographically with respect to binary comparison function object comp and projection function object proj. Returns {last, true} if such a “next permutation” exists; otherwise transforms the range into the lexicographically first permutation as if by ranges::sort(first, last, comp, proj), and returns {last, false}.
# Declarations
Call signature
template< std::bidirectional_iterator I, std::sentinel_for<I> S,
class Comp = ranges::less, class Proj = std::identity >
requires std::sortable<I, Comp, Proj>
constexpr next_permutation_result<I>
next_permutation( I first, S last, Comp comp = {}, Proj proj = {} );
(since C++20)
template< ranges::bidirectional_range R, class Comp = ranges::less,
class Proj = std::identity >
requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
constexpr next_permutation_result<ranges::borrowed_iterator_t<R>>
next_permutation( R&& r, Comp comp = {}, Proj proj = {} );
(since C++20)
Helper type
template< class I >
using next_permutation_result = ranges::in_found_result<I>;
(since C++20)
# Parameters
first, last: the range of elements to permuter: the range of elements to permutecomp: comparison function object which returns true if the first argument is less than the secondproj: projection to apply to the elements
# Notes
Implementations (e.g. MSVC STL) may enable vectorization when the iterator type models contiguous_iterator and swapping its value type calls neither non-trivial special member function nor ADL-found swap.
# Example
#include <algorithm>
#include <array>
#include <compare>
#include <functional>
#include <iostream>
#include <string>
struct S
{
char c;
int i;
auto operator<=>(const S&) const = default;
friend std::ostream& operator<<(std::ostream& os, const S& s)
{
return os << "{'" << s.c << "', " << s.i << "}";
}
};
auto print = [](auto const& v, char term = ' ')
{
std::cout << "{ ";
for (const auto& e : v)
std::cout << e << ' ';
std::cout << '}' << term;
};
int main()
{
std::cout << "Generate all permutations (iterators case):\n";
std::string s{"abc"};
do
{
print(s);
}
while (std::ranges::next_permutation(s.begin(), s.end()).found);
std::cout << "\n" "Generate all permutations (range case):\n";
std::array a{'a', 'b', 'c'};
do
{
print(a);
}
while (std::ranges::next_permutation(a).found);
std::cout << "\n" "Generate all permutations using comparator:\n";
using namespace std::literals;
std::array z{"█"s, "▄"s, "▁"s};
do
{
print(z);
}
while (std::ranges::next_permutation(z, std::greater()).found);
std::cout << "\n" "Generate all permutations using projection:\n";
std::array<S, 3> r{S{'A',3}, S{'B',2}, S{'C',1}};
do
{
print(r, '\n');
}
while (std::ranges::next_permutation(r, {}, &S::c).found);
}