仅供参考:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
static bool abs_compare(int a, int b)
{
return (std::abs(a) < std::abs(b));
}
int main()
{
std::vector<int> v{ 3, 1, -14, 1, 5, 9 };
std::vector<int>::iterator result;
result = std::max_element(v.begin(), v.end());
std::cout << "max element at: " << std::distance(v.begin(), result) << '\n';
result = std::max_element(v.begin(), v.end(), abs_compare);
std::cout << "max element (absolute) at: " << std::distance(v.begin(), result);
}
Output:
max element at: 5
max element (absolute) at: 2
#include <algorithm> // 包含算法头文件
// ...
const Student& highestScoreStudent = *std::max_element(students.begin(), students.end(),
[](const Student& s1, const Student& s2) {
return s1.getScore() < s2.getScore(); // 根据成绩进行比较
});
// ...
一个是没有包含头文件
一个是没有写比较谓语
#include <algorithm>
cout << "入学成绩最高学生:" << std::endl;
*max_element(students.begin(), students.end(), [](const Student& s1, const Student& s2) { return s1.entranceScore < s2.entranceScore; }).printfInfo();
功能:同min_element