Default (1) |
Template <class bidirectionaliterator> bool Next_permutation (bidirectionaliterator First, Bidirectionaliterator last); |
Custom (2) |
Template <class Bidirectionaliterator, class compare> bool Next_permutation (bidirectionaliterator First, Bidirectionaliterator last, Compare comp); |
Next_permutation is a function in the <algorithm> header file.
The STL provides two algorithms for calculating the permutations and combinations of relationships, namely Next_permutation and prev_permutation. First we must understand what is the "next" permutation, what is the "previous" permutation combination. Consider a sequence of three characters {a,b,c}.
This sequence has six possible permutation combinations: ABC,ACB,BAC,BCA,CAB,CBA. These permutations are sorted according to the Less-than operator in dictionary order (lexicographical) . That is, ABC is ranked first because each element is smaller than the element that follows it. ACB is the second permutation, because it is a new combination that is fixed after a (the smallest element in the sequence).
Similarly, the permutations of a fixed B (minor element in a sequence) are arranged in a sequence preceded by a permutation of the fixed C. Take BAC and BCA for example, BAC before BCA, because order AC is less than sequence ca. In the face of BCA, we can say that the previous permutation is a BAC, and then a permutation is a cab. The sequence ABC does not have a "previous" permutation combination, and the CBA does not have a "latter" permutation.
Next_permutation () takes the next permutation of the sequence indicated by [First,last] and returns False if there is no next permutation, otherwise true. There are two versions of this algorithm. Version one uses the Less-than operator provided by the element type to determine the next permutation combination, and version two is determined by the faux function comp.
Example
#include <stdio.h>#include<algorithm>using namespacestd;intMain () {intN; while(SCANF ("%d", &n) &&N) { inta[ +]; for(intI=0; i<n;i++) {scanf ("%d",&A[i]); } sort (A,a+N); Do{ for(intI=0; i<n;i++) printf ("%d", A[i]); printf ("\ n"); } while(Next_permutation (a,a+N)); } return 0;}
Input
3
0 1 2
Output
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
Next_permutation in C + + STL