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?
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.
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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.