Reputation: 1067
The problem:
#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;
}
How to find minimum value and position of var1[].cost? is it possible to find this using std::min_element?
Upvotes: 1
Views: 3100
Reputation: 18652
I can think of at least four ways to do this with std::min_element
1) Add a "less than" member function to the 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) Define a free function:
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) Define a function object type:
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) Create a lambda function:
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; });
}
Finally, use the returned iterator (pointer in this case) to print the value or offset:
std::cout << "Value = " << ptr->cost << '\n';
std::cout << "Position = " << (ptr - var1) << '\n'; // or std::distance(var1, ptr)
Upvotes: 3
Reputation: 75062
std::min_element - cppreference.com
You can use a comparision function object to have std::min_element
look at the member 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;
}
Upvotes: 3