I have a vector/container of classes and I want to find the element that has the max/min value of a specific member; for example:
#include <vector>
struct A {
int val;
};
int main() {
std::vector<A> v{{1},{2},{3}};
// how do I find the maximum of .val inside the vector?
}
Is there an "STL" way to find the item without explicitly iterating over the container and compare the values?
A comment on the two solutions
I'll add here a solution based on @Jarod42 comment on the accepted solution, based on std::ranges::less{} :
#include <iostream>
#include <vector>
#include <algorithm>
struct A {
int val1;
int val2;
};
int main()
{
std::vector<A> v{{6,8}, {4,10}, {5,12}};
// How can I find out the minimum and maximum?
const auto [min, max] = std::ranges::minmax_element(v, std::ranges::less{}, &A::val1);
std::cout << "Minimum Number: " << min->val1 << '\n';
std::cout << "Maximum Number: " << max->val1 << '\n';
}
I prefer this solution when the comparison to determine the min/max value is trivial, while the accepted solution is more generic and can be used when the definition of "less than" is complex.
Not sure if it needs C 20's ranges, but I'm using C 20 anyway so for the moment I won't investigate it any further.
CodePudding user response:
There are various ways:
For example:
auto smallest = std::min_element(v.begin(), v.end(), [](const A v1, const A v2) {
return v1.val < v2.val;
});
std::cout << "Smallest: " << smallest->val << "\n";