首页 > 编程语言 > 详细

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

时间:2021-03-03 14:45:50      阅读:24      评论:0      收藏:0      [点我收藏+]

转自: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());//上一个排列

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;

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

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

原文:https://www.cnblogs.com/BlueBlueSea/p/14473681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!