C++ STL标准库常用泛型算法

转自:https://www.cnblogs.com/wkfvawl/p/9475939.html,https://www.cnblogs.com/linuxAndMcu/p/10264339.html

1.二分查找

#include <algorithm>

//查找某个元素是否出现,返回布尔类型,找到value返回1,否则返回0,并不会返回下标
binary_search(arr[],arr[]+size ,value)//在数组中
binary_search(a.begin(),a.end(),value)//在向量中

//查找第一个大于等于某个值的迭代器,返回对应容器类型的iterator
lower_bound(arr[],arr[]+size , value)//在数组中

//查找第一个大于某值的迭代器,返回对应容器类型的iterator,找不到就指向end()
upper_bound(arr[],arr[]+size ,value)//在数组中

lower_bound()在查找value时如果在数组中出现了,那么就会返回第一个出现位置的下标,如果没有出现则它的功能和upper_bound一样。

例子:

#include <iostream>
#include<algorithm>
using namespace std;

int main(){
    vector<int> a={4,10,11,30,69,70,96,100};
    int b=binary_search(a.begin(),a.end(),4);//查找成功,返回1
    int c=binary_search(a.begin(),a.end(),69);//查找成功,返回1
    
    //10在数组中,12不在数组中
    int d=lower_bound(a.begin(),a.end(),10)-a.begin();//1 >=
    int f=upper_bound(a.begin(),a.end(),10)-a.begin();//2  >
    int e=lower_bound(a.begin(),a.end(),12)-a.begin();//3  >=
    int g=upper_bound(a.begin(),a.end(),12)-a.begin();//3  >

    //当存在重复元素时
    vector<int> a={10,20,30,30,20,10,10,20};
    sort(a.begin(), a.end());//二分查找需要在有序数组上进行
    //10 10 10 20 20 20 30 30
    int d=lower_bound(a.begin(),a.end(),10)-a.begin();//0 第一个>=
    int f=upper_bound(a.begin(),a.end(),10)-a.begin();//3
    int e=lower_bound(a.begin(),a.end(),12)-a.begin();//3
    int g=upper_bound(a.begin(),a.end(),12)-a.begin();//3
    return 0;
}

https://www.cnblogs.com/BlueBlueSea/p/13826493.html,我之前的这篇博客也记录了。

2.其他

//这些我用的不多

2.1排列组合

next_permutation(iv.begin(), iv.end());//下一个排列
prev_permutation(iv.begin(), iv.end());//上一个排列

https://blog.csdn.net/qian2213762498/article/details/79683905

next_permutation()会取得[first,last)所标示之序列的下一个排列组合,如果没有下一个排列组合,便返回false;否则返回true。

#include <iostream>
#include<algorithm>
using namespace std;
 
int main(int argc, char** argv) {
    int a[4]={1,2,3,4};
    sort(a,a+4);
    do{
        //cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<" "<<a[3]<<endl;
        for(int i=0;i<4;i++)
            cout<<a[i]<<" ";
        cout<<endl;
    }while(next_permutation(a,a+4));
    return 0;
}

应该是会做一个轮转的。

    vector<int> nums={4,3,2,1};
    next_permutation(nums.begin(),nums.end());
    for(auto& n:nums)
        cout<<n<<" ";
#输出
1 2 3 4 

2.2 数值算法

accumulate(vec.begin(), vec.end(), val);//求和,+val

2.3 关系算法

    // max_element: 返回一个ForwardIterator,指出序列中最大的元素。
    cout << "max_element: " << *max_element(iv1.begin(), iv1.end()) << endl;
    // min_element: 返回一个ForwardIterator,指出序列中最小的元素。
    cout << "min_element: " << *min_element(iv1.begin(), iv1.end()) << endl;

等等,没有放进来,等用到的时候再学习。

posted @ 2021-03-03 12:19  lypbendlf  阅读(101)  评论(0编辑  收藏  举报