<code class="tags" href="/tags/CLASS.html" title=class>class="language-cpp">#include <assert.h> #include <iostream> #include <algorithm> using namespace std; template<typename T> void Perm(T* pT, int n, int m) { if (n == m) { for (int i=0; i<m; i++) cout << pT[i] << " "; cout << endl; return; } else { for (int i=m; i<n; i++) { swap(pT[m], pT[i]); Perm(pT, n, m+1); swap(pT[m], pT[i]); } } } class="tags" href="/tags/CLASS.html" title=class>class Permutation { public: enum {MAX_SIZE = 10}; Permutation(int count) { assert(0 < count && count < MAX_SIZE); m_nCount = (char)count; for (char i=0; i<m_nCount; i++) m_Indexs[i] = i; } public: bool ToNext(); char operator[] (int n)const { assert(0 <= n && n <= m_nCount); return m_Indexs[n]; } private: char m_Indexs[MAX_SIZE]; char m_nCount; }; bool Permutation::ToNext() { char nReverse = m_nCount-1; while (nReverse > 0 && m_Indexs[nReverse]<m_Indexs[nReverse-1]) nReverse--; // 寻找第一个要交换的元素 if (nReverse == 0) // 找不到c;表示全排已经完成 return false; char nSwap = m_nCount - 1; while (m_Indexs[nSwap] < m_Indexs[nReverse-1]) nSwap--; // 寻找第二个元素 swap(m_Indexs[nReverse-1], m_Indexs[nSwap]); // 开始交换 reverse(m_Indexs+nReverse, m_Indexs+m_nCount); // 逆顺 return true; } int main() { const int N = 3; Permutation perm(N); const char* sTests[N] = {"aaa", "bbb", "ccc"}; do { for (int i=0; i<N; i++) cout << sTests[perm[i]] << " "; cout << endl; }while(perm.ToNext()); return 0; } code>