How can I get the minimum or maximum element in a vector of structures in C++, based on some field in the structure?
For example:
struct Size {
int width, height;
};
vector<Size> sizes;
And now I want to solve that based on width and create a new vector for that. And then sort based on height and create a new vector for that.
Min or Minimum element can be found with the help of *min_element() function provided in STL. Max or Maximum element can be found with the help of *max_element() function provided in STL.
To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element , respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element.
min() method. This method contains a single parameter i.e. the Vector whose minimum element is determined and it returns the minimum element from the Vector.
In C++11, you can use the std::minmax_element()
standard function, which (given a pair of iterators) and possibly a custom comparator (that would allow you to define the field on which the ordering is based), will return you an iterator to the minimum and an iterator to the maximum element, packed in an std::pair
.
So for instance:
#include <algorithm> // For std::minmax_element #include <tuple> // For std::tie #include <vector> // For std::vector #include <iterator> // For global begin() and end() std::vector<Size> sizes = { {4, 1}, {2, 3}, {1, 2} }; decltype(sizes)::iterator minEl, maxEl; std::tie(minEl, maxEl) = std::minmax_element(begin(sizes), end(sizes), [] (Size const& s1, Size const& s2) { return s1.width < s2.width; });
Here is a live example.
You can use std::min_element and std::max_element
with a suitable functor:
bool cmp(const Size& lhs, const Size& rhs) { return lhs.width < rhs.width; }
then
auto min_it = std::min_element(sizes.begin(), sizes.end(), cmp); auto max_it = std::max_element(sizes.begin(), sizes.end(), cmp);
In C++11 you can replace cmp
with a lambda expression.
See also: std::minmax_element
vector<Size> sizes;
...
vector<Size> sortedByWidths(sizes);
vector<Size> sortedByHeights(sizes);
sort(sortedByWidths.begin(), sortedByWidths.end(),
[](Size s1, Size s2) {return s1.width < s2.width;});
sort(sortedByHeights.begin(), sortedByHeights.end(),
[](Size s1, Size s2) {return s1.height< s2.height;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With