c++中的min_element()与max_element()

c++中的min_element()与max_element()

头文件: #include<algorithm>

**作用:**返回容器中的最小值或者最大值的迭代器(迭代器可以理解为指针)

举例如下

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

bool cmp(int a, int b)
{
    return a < b;
}

int main()
{
    vector<int> ints = {5, 3, 90, 32, 24, 56, 98, 54, 76, 45, 89, 100};
    auto min_iterator = min_element(ints.begin(), ints.end(), cmp);
    cout << *min_iterator << endl;	//输出为 3 ,此时的min_iterator为迭代器,需要解引用才能获得最小值
    return 0;
}
//--------------------------------------------------------------
//当然,这个比较函数(cmp)也可以直接用无名函数代替,如下代码所示:
int main()
{
    vector<int> ints = {5, 3, 90, 32, 24, 56, 98, 54, 76, 45, 89, 100};
    auto min_iterator = min_element(ints.begin(), ints.end(), [](int a, int b)
    {
        return a < b;
    }
    );
    cout << *min_iterator << endl;  //同样输出 3 
    return 0;
}
//----------------------------------------------------------------
//定义一个学生类
class Student
{
public:
    string name_;
    int age_;

    Student()
    {}

    Student(string name, int age):
    name_(name), age_(age)
    {}

};

int main()
{
    vector<Student> students;

    students.push_back(Student("zhangsan",23));
    students.push_back(Student("lisi",20));
    students.push_back(Student("wangwu",34));
    students.push_back(Student("zhaoliu",27));
    students.push_back(Student("jerry",19));

    string student_who_has_min_age = min_element(students.begin(), students.end(), [](const Student& s1, const Student& s2)
    {
        return s1.age_ < s2.age_;
    }
    )->name_;

    cout << student_who_has_min_age << endl;    //输出: jerry
    return 0;
}
/**
 * 上述这段代码的含义是用无名函数取代 cmp,并且取运算出来的符合要求的迭代器的name属性:->name_ 
 */
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值