一些好用的c++ STL库函数

stl可以说是懒癌患者福利了// 持续更新(随缘更新

全排列函数next_permutation

今天在洛谷做题的时候发现一个题简直是这个函数的完美应用
题目链接:洛谷P1088 火星人

头文件:#include < algorithm >

时间复杂度 :O(n)

函数原型:

     bool next_permutation(iterator start,iterator end)

该函数的作用是求全排列的下一项(这里其实还有一个prev_permutation函数是求上一项的,除此之外用法相同)这里的下一项指的是字典序列的下一项,如果存在下一项函数的返回值是true,不存在下一项返回false

下面来看个例子

#include 
#include 
using namespace std;
int main()
{
    char num[3]={'a','b','c'};
    do
    {
        cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;
    }while(next_permutation(num,num+3));
    return 0;
}  

这里对a,b,c进行全排列

输出结果:

一些好用的c++ STL库函数_第1张图片

需要注意的是这里num数组的初始化会对输出结果产生影响,因为该函数求的是下一个序列,所以如果初始数组不是按字典序第一个数组的话便不会再去便利之前的序列

比如说

char num[3]={'b','a','c'};

我们把num数组初始化过程中的a和b调换位置之后输出结果变为
在这里插入图片描述

突然发现next_permutation甚至可以自己重写cmp函数(这也太好用了吧)

贴个例子吧

int cmp(char a,char b) 
{
 if(tolower(a)!=tolower(b))//tolower 是将大写字母转化为小写字母.
 return tolower(a)<tolower(b);
 else
 return a<b;
}

另外附上开头那道题的AC代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
typedef long long ll;
#define MAXN 500010
using namespace std;
int a[10010];
int main()
{
    int n,m;
    cin >> n >> m;
    for (int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    for (int i=1;i<=m;i++)
        next_permutation(a+1, a+n+1);
    for (int i=1;i<n;i++)
        printf("%d ",a[i]);
    cout << a[n] << endl;
}

二分查找有关函数lower_bound upper_bound和 binary_search

时间复杂度:O(logn) 因为是二分

用法:

lower_bound( begin,end,num): 从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

upper_bound( begin,end,num): 从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

在从大到小的排序数组中,重载lower_bound()和upper_bound()

lower_bound( begin,end,num,greater() ): 从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

upper_bound( begin,end,num,greater() ): 从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

下面介绍几个单参数的用法

lower_bound(val): 返回容器中第一个值【大于或等于】val的元素的iterator位置。
功能:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置.

注意:如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!

upper_bound(val): 返回容器中第一个值【大于】val的元素的iterator位置。
功能:函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置

注意:返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置。同样,如果val大于数组中全部元素,返回的是last。(注意:数组下标越界)

你可能感兴趣的:(语法工具整理)