<algorithm>与<vector>,cpp标准模板库算法,部分代码理解三

1 sort:排序;

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int main(){
    vector<int>a={1,3,5,4,2};
    vector<string>c={"wangzihen","ludafu","yanjunnan"};
    sort(c.begin(),c.end());
    sort(a.begin(),a.end());
    for(const auto &i:a){
        cout<<i<<" ";
    }
    cout<<endl;
    for(const auto &i:c){
        cout<<i<<" ";
    }
    return 0;
}主要是在于对迭代器的理解,auto自动变量

f5711bac9f484cf5bc882dd45a972ebf.png

2 pratial_sort:

确保前n个最小的元素以升序排序,其余元素位置不定

 partial_sort(a.begin(),a.begin()+3,a.end());
  //只确保前3个最小的元素以升序排序,其余元素位置不定。

8726e067e6244601973f5fd014f75b2b.png

可以看出4,5并没有排序;

3 .1lower_bound:查找有序序列中第一个不小于给定值的元素。

auto it=lower_bound(a.begin(),a.end(),4);
cout<<*it<<endl;

根据之前我们知道find_if也是查找容器中的函数,那lower_bouend的好处的主要是时间复杂度,它的时间复杂度为O(log n),而find的时间复杂度为O(n);但是find的用处更广,可以用于未排序的容器。

18286aff48954f65abd10cc612843730.png

3.2upper_bound:查找有序序列中第一个大于给定值的元素

auto it=upper_bound(a.begin(),a.end(),2);
cout<<*it<<endl;

19b48e2a4fe14900bf404b6fc59b1e28.png

3.3binary_search:

 在有序序列中查找给定值

       if(binary_search(c.begin(),c.end(),"yanjunnan")){
           cout<<"he is ungly";
       }
       else{
           cout<<"he is handsame";
       }

3ed88fa9e4be4b3dbc30375bd2ebe3d1.png

4.1 max,min:返回最大或最小;

     b=max(a,b);
     b=min(a,b);
     for(const auto &i:b){
         cout<<i;
     }

4.2 max_element,min_element:  在一个范围内查找最大或最小的元素。

    auto ma=max_element(c.begin(),c.end());
    auto mi=min_element(c.begin(),c.end());
    cout<<*ma<<"  "<<*mi<<endl;

30502f3e26184df9b910d28be84d7c9d.png

 

 

 

 

 

  • 15
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值