关于next_permutation函数和lower_bound函数

next_permutation:

这个函数是一个C++函数,头文件#include<algorithm>, 可以产生1~n的全排列

  • 一般用法 
int a[];
do{

}while(next_permutation(a,a+n));

对于数组:

int b[10]={1,2,3};
    do{
        for(int i=0;i<3;i++)
            printf("%d ",b[i]);
        printf("\n");
    }while(next_permutation(b,b+3));

输出:

(有序)

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

int b[10]={2,1,3};
    do{
        for(int i=0;i<3;i++)
            printf("%d ",b[i]);
        printf("\n");
    }while(next_permutation(b,b+3));

输出:

(无序)

 2 1 3

2 3 1

3 1 2

3 2 1

输出都是按照字典序输出


lower_bound:

C++函数,包含头文件#include<algorithm>,功能为查找大于或者等于给定元素的位置。

用法1(针对数组):

判断位置:

int main()
{
    int a[]={1,2,3,4,5};
    int h=lower_bound(a,a+5,3)-a;
    printf("%d %d\n",h,a[h]);
    return 0;
}

输出:

2,3

输出元素本身的值:

int main()
{
    int a[]={1,2,3,4,5};
    int *h=lower_bound(a,a+5,3);
    printf("%d\n",*h);
    return 0;
}

输出:

3

用法2(针对容器):

int main()
{
    vector<int> a;
    for(int i=0;i<=4;i++)
        a.push_back(i);
    vector<int>::iterator it=lower_bound(a.begin(),a.end(),3);
  //  int pos=it-a.begin();
    cout<<*it<<endl;
    return 0;
}

输出为元素本身的值,如果要判断位置加上注释的语句修改输出即可。

用法3(加上自定义函数)

对于四个参数的函数,最后一个函数为自定义比较函数。

int main()
{
    int a[]={8,4,6,2};
    int pos=lower_bound(a,a+4,3,greater<int>())-a;
    printf("%d %d\n",pos,a[pos]);
    return 0;
}

逆序才行.

猜你喜欢

转载自blog.csdn.net/qwerqwee12/article/details/81303857