Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the largest object, based on an attribute, from a vector?

Tags:

c++

stl

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?

like image 379
Sheila Avatar asked Oct 30 '10 20:10

Sheila


2 Answers

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; });
like image 84
James McNellis Avatar answered Nov 04 '22 08:11

James McNellis


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.

like image 1
Khaled Alshaya Avatar answered Nov 04 '22 08:11

Khaled Alshaya