问题:
#include <iostream>
#include <algorithm>
using namespace std;
struct abc
{
int cost;
int any;
};
int main() {
abc *var1 = new abc[5];
var1[0].cost = 4;
var1[1].cost = 42;
var1[2].cost = 5;
var1[3].cost = 0;
var1[4].cost = 12;
// cout<< "value = " << *std::min_element(var1.cost,var1.cost+5) << endl;
// cout << "Position = " << (std::min_element(var1.cost,var1.cost+5)-var1.cost) << endl;
return 0;
}
如何找到var1 []。cost的最小值和位置?是否可以使用std :: min_element找到它?
答案 0 :(得分:3)
std::min_element - cppreference.com
您可以使用比较函数对象让std::min_element
查看成员cost
。
#include <iostream>
#include <algorithm>
using namespace std;
struct abc
{
int cost;
int any;
};
struct cmp_abc {
bool operator()(const abc& a, const abc& b) const {
return a.cost < b.cost;
}
};
int main() {
abc *var1 = new abc[5];
var1[0].cost = 4;
var1[1].cost = 42;
var1[2].cost = 5;
var1[3].cost = 0;
var1[4].cost = 12;
abc *res = std::min_element(var1, var1 + 5, cmp_abc());
cout << "value = " << res->cost << endl;
cout << "Position = " << (res - var1) << endl;
delete[] var1;
return 0;
}
答案 1 :(得分:2)
我可以通过std::min_element
1)在struct / class中添加一个“小于”的成员函数:
struct abc
{
int cost;
int any;
bool operator<(const abc &other) const { // member function
return cost < other.cost;
}
};
int main() {
// ...
// The algorithm will find and use the class operator< by default
abc *ptr = std::min_element(var1, var1 + 5);
}
2)定义一个自由函数:
bool abc_less(const abc &lhs, const abc &rhs) // free function
{
return lhs.cost < rhs.cost;
}
int main() {
// ...
// Pass a function pointer to the algorithm
abc *ptr = std::min_element(var1, var1 + 5, abc_less);
}
3)定义一个函数对象类型:
struct abc_less // function object
{
bool operator()(const abc &lhs, const abc &rhs) const {
return lhs.cost < rhs.cost;
}
};
int main() {
// ...
// Construct and pass a function object to the algorithm
abc *ptr = std::min_element(var1, var1 + 5, abc_less());
}
4)创建一个lambda函数:
int main() {
// ...
// Create a lambda at the point of call in this example
abc *ptr = std::min_element(var1, var1 + 5, [](const abc &lhs, const abc &rhs) { return lhs.cost < rhs.cost; });
}
最后,使用返回的迭代器(在本例中为指针)来打印值或偏移量:
std::cout << "Value = " << ptr->cost << '\n';
std::cout << "Position = " << (ptr - var1) << '\n'; // or std::distance(var1, ptr)