The STL provides 2 algorithms for calculating permutations and combinations of relationships. Next_permucation and Prev_permutaion, respectively.
Next_permutation is used to calculate the composition of the next dictionary order, and Prev_permutation is used to calculate the permutation of the previous (prev) dictionary order.
Dictionary sorting refers to the arrangement of permutations, sorted by size from small to large, such as the 123 arrangement, and the dictionary sort to 123,132,213,231,312,321.
Take a look at the implementation principle of next_permutation:
Looking forward from the back of the sequence, found two adjacent elements P[n] and p[n+1], and P[n]
Template < class _bidirectionaliter>bool next_permutation(_bidirectionaliter __first, _bidirectionaliter __last) {__stl_requires (_bidirectionaliter, _bidirectionaliterator); __stl_requires (TypeName Iterator_traits<_bidirectionaliter>::value_type, _lessthancomparable);if(__first = = __last)//Empty collection return false; _bidirectionaliter __i = __first; ++__i;if(__i = = __last)//Only one element return false; __i = __last; --__i;//Last element for(;;) {_bidirectionaliter __ii = __i; --__i;if(*__i < *__ii) {//Find p[n]<p[n+1]_bidirectionaliter __j = __last; while(! (*__i < *--__j))//Find P[m]{} iter_swap (__i, __j);Reverse(__ii, __last);//Reverse sort return true; }if(__i = = __first) {//arrive at the front not to find meet p[n]<p[n+1], lined up Reverse(__first, __last);return false; } }}
For custom types, the comparison size can be passed into the function pointer, and the prototype is:
first, last, Compare comp);
Test:
#include <iostream>#include <vector>#include <algorithm>voidPrint (STD:: vector<int>& V) { for(STD:: vector<int>:: Iterator It=v.begin (); It!=v.end (); ++it) {STD::cout<<*it<<" "; }STD::cout<<STD:: Endl;}intMain () {STD:: vector<int>V V.reserve (5); for(intI=1; i<=5; ++i) {v.push_back (i); } Do{Print (V); } while(STD:: Next_permutation (V.begin (), V.end ()));return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"STL Source Code Analysis"--next_permutation function