// next_permutation.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <algorithm> #include <vector> #include <iostream> #include <functional> using namespace std; /************************************************/ template<class _BI> inline bool MY_next_permutation(_BI _F, _BI _L) { _BI _I = _L; //只有一个元素或者只有两个元素 if (_F == _L || _F == --_I) return (false); for (; ; ) { //最后一个元素之前的元素 _BI _Ip = _I; //最后一个元素之前之前的元素(小于)最后一个元素之前的元素。就交换和倒序 if (*--_I < *_Ip) { _BI _J = _L;//最后一个元素 //最后一个元素前面的元素(前面的前面)的值与 for (; !(*_I < *--_J); ) ; iter_swap(_I, _J); reverse(_Ip, _L);//当前迭代器和last迭代器之前的数据倒序 return (true); } //最后一个元素之前的元素的迭代器如果到了开头,就再倒序一下 if (_I == _F) { reverse(_F, _L); return (false); } } } /***************************************************/ void print_char( char elem ) { cout << elem ; } void (*ppc)( char ) = print_char; int main(int argc, char* argv[]) { vector<char> vec(5); // 字符顺序: musil vec[0] = 'm'; vec[1] = 'u'; vec[2] = 's'; vec[3] = 'i'; vec[4] = 'l'; int cnt = 2; //如果倒序列的话,只有输出一个 //sort( vec.begin(), vec.end(),greater<char>() ); sort( vec.begin(), vec.end(),less<char>() ); for_each( vec.begin(), vec.end(), ppc ); cout << "/t"; // 生成 "musil" 的所有排列组合 while( next_permutation( vec.begin(), vec.end())) { for_each( vec.begin(), vec.end(), ppc ); cout << "/t"; if ( ! ( cnt++ % 8 )) { cout << "/n"; cnt = 1; } } cout << "/n/n"; return 0; } prev_permutation() // prev_permutation.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <algorithm> #include <vector> #include <iostream> using namespace std; template<class _BI> inline bool my_prev_permutation(_BI _F, _BI _L) { _BI _I = _L; if (_F == _L || _F == --_I) return (false); for (; ; ) { _BI _Ip = _I; if (!(*--_I < *_Ip)) { _BI _J = _L; for (; *_I < *--_J; ) ; iter_swap(_I, _J); reverse(_Ip, _L); return (true); } if (_I == _F) { reverse(_F, _L); return (false); } } } //这些排列根据less_than 小于操作符做一个排序 // 输出: // n d a n a d d n a d a n a n d a d n int main(int argc, char* argv[]) { vector< char > vec( 4 ); ostream_iterator< char > out_stream( cout, " " ); vec[0] = 'n'; vec[1] = 'd'; vec[2] = 'b', vec[3] = 'a'; copy( vec.begin(), vec.end(), out_stream ); cout << "/t"; // 生成 "dan" 的所有排列 while( my_prev_permutation( vec.begin(), vec.end() )) { copy( vec.begin(), vec.end(), out_stream ); cout << "/t"; } cout << "/n/n"; return 0; }