STL next——permutation函数 求数列的全排列

来源:互联网 发布:数据预测方法 编辑:程序博客网 时间:2024/05/16 10:57

在C++的标准函数库STL中,next_permutation()函数用于求数列的全排列。

代码:

例子1(int型):
int main(){
    int a[] = {3,1,2};
    do{
        cout << a[0] << " " << a[1] << " " << a[2] << endl;
    }while (next_permutation(a, a+3));
    return 0;
}
输出:312/321  因为原数列不是从最小字典排列开始。
所以要想得到所有全排列
int a[] = {3,1,2}; 然后先排序为:a[] = {1,2,3};
例子2(string型)
int main(){
    string str;
    cin >> str;
    sort(str.begin(), str.end());
    do{
        cout << str << endl;
    }while (next_permutation(str.begin(), str.end()));
    return 0;
}
库中另一函数prev_permutation()与next_permutation()相反



0 0