Let's say I have a bunch of Donut
objects, and each of these donuts has a public integer attribute diameter
. If I have a vector of donuts, how can I extract the donut with the smallest or largest diameter?
You use std::min_element
and std::max_element
. For example, given a std::vector<int>
:
std::vector<int> v;
std::vector<int>::iterator it = std::max_element(v.begin(), v.end());
// 'it' points to the largest element in 'v'
If you want to compare elements using something other than operator<
(which is used by default), you need to write a custom comparator:
bool compare_donut_diameters(const Donut& x, const Donut& y)
{
return x.diameter < y.diameter;
}
Used as:
std::vector<Donut> v;
std::vector<Donut>::iterator it = std::max_element(v.begin, v.end(),
compare_donut_diameters);
You can also implement the comparator using a function object (also called a functor) or if your compiler supports lambda expressions you can use a lambda:
auto it = std::max_element(v.begin(), v.end(),
[](const Donut& x, const Donut& y) { return x.diameter < y.diameter; });
You can use std::min_element
:
// You can use a functor instead!
bool compare_donut(const Donut& lhs, const Donut& rhs)
{ return lhs.diameter < rhs.diameter; }
...
// min_donut is an iterator to the smallest donut in donut_vector.
std::vector<Donut>::iterator min_donut =
std::min_element(donut_vector.begin(), donut_vector.end(), compare_donut);
If you want to get the largest, you can use std::max_element
with the same comparator.
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