std::prev_permutation

Header: <algorithm>

Transforms the range [first,last) into the previous permutation. Returns true if such permutation exists, otherwise transforms the range into the last permutation (as if by std::sort followed by std::reverse) and returns false.

# Declarations

template< class BidirIt >
bool prev_permutation( BidirIt first, BidirIt last );

(constexpr since C++20)

template< class BidirIt, class Compare >
bool prev_permutation( BidirIt first, BidirIt last, Compare comp );

(constexpr since C++20)

# Parameters

# Return value

true if the new permutation precedes the old in lexicographical order. false if the first permutation was reached and the range was reset to the last permutation.

# Notes

Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call.

Implementations (e.g. MSVC STL) may enable vectorization when the iterator type satisfies LegacyContiguousIterator and swapping its value type calls neither non-trivial special member function nor ADL-found swap.

# Example

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

# See also