C++排序&求最值函数的调用

c++对于vector等类型的数据处理,经常会涉及到排序,顺序,逆序,或者根据某一个每一个条件排序.今天来捋一捋

==> 实际上发现已经有英文的整理版本,附上链接

1.实现vector元素的顺序排列


// C++ program to sort a vector in non-decreasing
// order.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
  
    sort(v.begin(), v.end());
  
    cout << "Sorted \n";
    for (auto x : v)
        cout << x << " ";
  
    return 0;
}

2. 实现vector元素的逆序排列


// C++ program to sort a vector in non-increasing
// order.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
  
    sort(v.begin(), v.end(), greater<int>());
  
    cout << "Sorted \n";
    for (auto x : v)
        cout << x << " ";
  
    return 0;
}

template <class T> struct greater : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const {return x>y;}
};

其实,这就是一个标准库自带的函数模板,如果我们用less<int>作为第三个参数,那么就是顺序排列

3. 按照某一属性排列

对于一个对象,我们希望按照它的某一个属性进行排列,那要怎么实现呢?

其实根据第二个例子,就知道原理就是定义一个bool函数,设定比较的规则

"比较函数"的关键:
形参: 要比较的对象

返回值: bool

规则:

less==>true :ascending  升序排列

greater==>true: descending 降序排列

下面的代码: 我们要排列car这个对象,其中根据它的属性 position

struct也可以设置constuctor哦

/*************************************************************************
	> File Name: struct_sort.cpp
	> Author: 
	> Mail: 
	> Created Time: So 25 Jul 2021 20:31:53 CEST
 ************************************************************************/
#include <algorithm>
#include <vector>
#include<iostream>
using namespace std;


struct car{
    double speed;
    double position;
    car(double speed, double position):speed(speed),position(position)
    {
        speed = speed;
        position = position;
    }
    
};

bool comparecar(car& car1,car& car2)
{
    return (car1.position<car2.position);//less =>ascending 
}

int main()
{
    vector<car> fleet{{1,3},{4,2},{3,5},{6,7},{2,9}};
    sort(fleet.begin(),fleet.end(),comparecar);
    for (auto x:fleet)
    {
        cout<<x.position<<"   "<<x.speed<<endl;
    }
    
}

4. 反向遍历

用迭代器,我们也可以实现对于vector的反向遍历,比如

这就可以用rbegin和rend实现元素的反向遍历 

5. 求最值

我们想求一个vector中的最大最小值, c++也提供了对应的函数

/*************************************************************************
	> File Name: getVecMin.cpp
	> Author: 
	> Mail: 
	> Created Time: Mo 26 Jul 2021 08:43:02 CEST
 ************************************************************************/
#include <vector>
#include <algorithm>
#include<iostream>
using namespace std;

int main()
{
    vector<int> array ={1,5,4,5,6,3,22,99};
    cout<<"Max "<<*max_element(array.begin(),array.end())<<endl;
    cout<<"Min "<<*min_element(array.begin(),array.end())<<endl;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值