Next_permutation gets the next arrangement, for example, for sequence a, B, c, each element is smaller than the following, and its next sequence is A, C, B
The following is a prototype of next_permutation:
Template <class bidirectionaliterator>
Bool next_permutation (
Bidirectionaliterator _ first,
Bidirectionaliterator _ last
);
Template <class bidirectionaliterator, class binarypredicate>
Bool next_permutation (
Bidirectionaliterator _ first,
Bidirectionaliterator _ last,
Binarypredicate _ comp
);
The function implementation principle is as follows:
In the current sequence, two adjacent elements are searched from the tail end. The first element is counted as * I, and the last element is counted as * T, which satisfies * I <* t. Then, find another element, * j, from the end. If * I <* j is satisfied, the I and j elements are reversed, sort all the elements after the nth element (including T) in reverse order to find the next sequence.
Template <class bidirectionaliterator>
Bool next_permutation (
Bidirectionaliterator first,
Bidirectionaliterator last
)
{
If (first = last)
Return false; // empty Sequence
Bidirectionaliterator I = first;
++ I;
If (I = last)
Return false; // an element with no next sequence
I = last;
-- I;
For (;;){
Bidirectionaliterator T = I;
-- I;
If (* I <* t ){
Bidirectionaliterator J = last;
While (! (* I <* -- j ));
Iter_swap (I, j );
Reverse (T, last );
Return true;
}
If (I = first ){
Reverse (first, last); // reverse all, that is, the smallest dictionary sequence. For example, the CBA becomes ABC.
Return false;
}
}
}
Therefore, if next_permutation is arranged in the last arrangement, false is returned. However, after this method is used, the sequence becomes the first dictionary sequence, for example, CBA becomes ABC. Can continue next, can refer to next_permutation usage, http://blog.csdn.net/hongchangfirst/article/details/8663899
In STL, apart from next_permutation, there is also a function prev_permutation, both of which are used to calculate the function of permutation and combination. The former is to find the next permutation and combination, while the latter is to find the last permutation and combination.
Reprinted please indicate the source:
Original article: http://blog.csdn.net/hongchangfirst/article/details/8672183
Author: hongchangfirst