C++STL算法篇之min_element、max_element 最小值和最大值返回算法

min_element(iter1,iter2)和min_element(iter1,iter2,op)的特点

1:返回指向区间[iter1,iter2)中最小值元素位置的迭代器
2:无op版本,以operator<比较,有op版本,以op(elem1,elem2)比较
3:op不应该改动传入的参数
4:如果存在多个最小值则返回第一个找到的最小值
5:迭代器类型:输入迭代器

#include
#include
#include
using namespace std;

class people
{
private:
	int age; //年龄
	string name; //名字

public:
	people(int Age = 0, string Name = " ") :age(Age), name(Name) {}
	void print()
	{
		cout << "name:" << name << "  age:" << age << endl;
	}
	bool operator<(const people& P)const
	{
		return age < P.age;
	}

	int reage()const
	{
		return age;
	}
};

int main()
{
	vector<int>c1 = { 1,2,3,99,4,0,5,6,7,8,9 };
	cout << *min_element(c1.begin(), c1.end()) << endl;
	
	vector<people>c2 = { people(20,"A"),people(25,"B"), people(30,"C"),  people(10,"D"), people(40,"E")};
	
	vector<people>::iterator itpeople = min_element(c2.begin(), c2.end(),
	 [](const people&p1, const people& p2)->bool { return p1.reage() < p2.reage(); });

	itpeople->print();


//如果自定义类中有重载operator<操作符 可之间使用第一种无op版本
 //vector::iterator itpeople = min_element(c2.begin(), c2.end());
}

**op推荐采用lambdas表达式:lambdas的使用方法
**

min_element(iter1,iter2)min_element(iter1,iter2,op) 的使用同上

你可能感兴趣的:(C++学习笔记)