prev_permutation() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). prev_permutation() is a method in the STL that rearranges the elements in a given range to the previous lexicographically ordered permutation.


prev_permutation( iterator_begin, iterator_end );
prev_permutation( iterator_begin, iterator_end, comparator );

Parameters: The prev_permutation() method accepts 3 parameters

  • iterator_begin: Iterator to the initial position
  • iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: True if the function could rearrange the object as a lexicographically smaller permutation. False otherwise

Example of prev_permutation() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void printv(vector<int> v)
    for( vector<int>::iterator it = v.begin(); it != v.end(); ++it)
        cout<< *it <<"   ";

int main()
    vector<int> v;


    while( prev_permutation(v.begin(),v.end()) )


3  2  1
3  1  2
2  3  1
2  1  3
1  3  2
1  2  3

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]