std::next_permutation

From cppreference.com
< cpp‎ | algorithm
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Concepts and utilities: std::Sortable, std::projected, ...
Constrained algorithms: std::ranges::copy, std::ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
(C++11)(C++11)(C++11)
(C++17)
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
(C++11)
Binary search operations
Set operations (on sorted ranges)
Heap operations
(C++11)
Minimum/maximum operations
(C++11)
(C++17)
Permutations
next_permutation
Numeric operations
C library
 
Defined in header <algorithm>
(1)
template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
(until C++20)
template< class BidirIt >
constexpr bool next_permutation( BidirIt first, BidirIt last );
(since C++20)
(2)
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );
(until C++20)
template< class BidirIt, class Compare >
constexpr bool next_permutation( BidirIt first, BidirIt last, Compare comp );
(since C++20)

Transforms the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered with respect to operator< or comp. Returns true if such permutation exists, otherwise transforms the range into the first permutation (as if by std::sort(first, last)) and returns false.

Parameters

first, last - the range of elements to permute
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than the second.

The signature of the comparison function should be equivalent to the following:

 bool cmp(const Type1 &a, const Type2 &b);

While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy (since C++11)).
The types Type1 and Type2 must be such that an object of type BidirIt can be dereferenced and then implicitly converted to both of them. ​

Type requirements
-
BidirIt must meet the requirements of ValueSwappable and LegacyBidirectionalIterator.

Return value

true if the new permutation is lexicographically greater than the old. false if the last permutation was reached and the range was reset to the first permutation.

Exceptions

Any exceptions thrown from iterator operations or the element swap.

Complexity

At most N/2 swaps, where N = std::distance(first, last). Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call.

Possible implementation

template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;
 
    while (true) {
        BidirIt i1, i2;
 
        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

Example

The following code prints all three permutations of the string "aba"

#include <algorithm>
#include <string>
#include <iostream>
 
int main()
{
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << '\n';
    } while(std::next_permutation(s.begin(), s.end()));
}

Output:

aab
aba
baa

See also

determines if a sequence is a permutation of another sequence
(function template)
generates the next smaller lexicographic permutation of a range of elements
(function template)