STL的排列函数及字符串的排序方法

Posted 启动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了STL的排列函数及字符串的排序方法相关的知识,希望对你有一定的参考价值。

next_permutation(a,a+n);   a代表数组的头地址,a+n代表数组的长度。

运用该函数,a数组将变成原排列的下一个排列。

与之相反的函数为prev_permutation(a,a+n);

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

int f(int n) {
    int sum = 1;
    for(int i = 2; i <= n; i++)
        sum *= i;
    return sum;
}
int main() {
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int a[10];
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++) {
        a[i] = i;
    }
    for(int i = 1; i <= f(n); i++)    {
        for(int j = 1; j <= n; j++)
            cout << a[j];
        next_permutation(a+1,a+n+1);    //prev_permutation(a+1,a+n+1);
        cout << endl;
    }
    return 0;
}

 

上面是int型,下面的char型和string型的写法

第一行为输入,后面几行为输出,上题的整型输出类似

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

int f(int n) {
    int sum = 1;
    for(int i = 2; i <= n; i++)
        sum *= i;
    return sum;
}
int main() {
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    string b; //char a[100];
    cin >> b; //scanf("%s",a);
    sort(b.begin(), b.end()); //sort(a, a+stlen(a));
    for(int j = 1; j <= f(b.length()); j++) {// f(strlen(a))
        cout << b << endl; // printf("%s\\n",a);
    next_permutation(b.begin(),b.end()); // next_permutation(a, a+strlen(a));    
    }
    return 0;
}

 

以上是关于STL的排列函数及字符串的排序方法的主要内容,如果未能解决你的问题,请参考以下文章

51Nod 1384 全排列

STL中的全排列实现

C++STL的next_permutation

STL——容器(Map & multimap)的排序

STL之next_permutation函数对各种类型的全排列实例

关于计数排列(模板)