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_
*/
}