next_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). next_permutation() is a method in the STL that rearranges the elements in a given range to the next lexicographically greater permutation.


next_permutation( iterator_begin, iterator_end );
next_permutation( iterator_begin, iterator_end, comparator );

Parameters: The next_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 greater permutation. False otherwise

Example of next_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( next_permutation(v.begin(),v.end()) )


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

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