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?
views:
58answers:
4You can sort the contents of the vector and then pick out the smallest or largest value.
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.
You could use the std::max_element/std::min_element algorithm in combination with an operator< that compares using the diameter attribute or an user provided compare function.
http://www.cplusplus.com/reference/algorithm/max_element/
http://www.cplusplus.com/reference/algorithm/min_element/
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; });