tags:

views:

58

answers:

4

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?

A: 

You can sort the contents of the vector and then pick out the smallest or largest value.

Als
+1  A: 

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.

AraK
+1  A: 

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/

nabulke
+6  A: 

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; });
James McNellis
Yep, it's certainly going to take a while to figure out how to use lambda functions in 80 columns ;-)
Steve Jessop
@Steve: Seriously! I think I reformatted that last example four times... It's a good thing widescreen displays are more prevalent. 240 character lines here I come!
James McNellis
c++0x looks so foreign... "auto", anonymous functions... pfft :-)
bjoernz