获取一个数组中的最大值和最小值,通过匿名函数声明自定义比较策略。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#define BUFSIZE 6
using namespace std;
typedef struct
{
std::string name;
int distance;
}vi;
int main()
{
//create dataset
vi vi_data;
std::vector<vi> vi_vector;
std::array<std::string,BUFSIZE> names = {"a","b","c","d","e","f"};
std::array<int,BUFSIZE> distances= {4,8,2,90,54,23};
for(int i = 0; i < BUFSIZE; i++){
vi_data.name = names[i];
vi_data.distance = distances[i];
vi_vector.push_back(vi_data);
}
//get min and max vi through compare vi.distance
std::pair<std::vector<vi>::iterator,std::vector<vi>::iterator> minmax; //auto
minmax = std::minmax_element(vi_vector.begin(),vi_vector.end(),
[](const vi &m1, const vi &m2){
return m1.distance < m2.distance;
});
std::cout << "min distance = " << minmax.first->distance<<endl;
std::cout << "max distance = " << minmax.second->distance<<endl;
exit(0);
}
标签:std,distance,vi,element,vector,minmax,data
From: https://www.cnblogs.com/hezexian/p/17287954.html