I have trouble describing my problem so I'll give an example:
I have a class description that has a couple of variables in it, for example:
class A{
float a, b, c, d;
}
Now, I maintain a vector<A>
that contains many of these classes. What I need to do very very often is to find the object inside this vector that satisfies that one of it's parameters is maximal w.r.t to the others. i.e code looks something like:
int maxi=-1;
float maxa=-1000;
for(int i=0;i<vec.size();i++){
res= vec[i].a;
if(res > maxa) {
maxa= res;
maxi=i;
}
}
return vec[maxi];
However, sometimes I need to find class with maximal a
, sometimes with maximal b
, sometimes the class with maximal 0.8*a + 0.2*b
, sometimes I want a maximal a*VAR + b
, where VAR
is some variable that is assigned in front, etc. In other words, I need to evaluate an expression for every class, and take the max
. I find myself copy-pasting this everywhere, and only changing the single line that defines res
.
Is there some nice way to avoid this insanity in C++? What's the neatest way to handle this?
Thank you!
You need to include
<functional>
for this to work. Now use, from header<algorithm>
or
and
or even
with
to compare by
a
member or by linear combinations ofa
andb
members. I split the comparer in two because themem_ptr
thing is damn useful and worth being reused. The return value ofstd::max_element
is an iterator to the maximum value. You can dereference it to get the max element, or you can usestd::distance(v.begin(), i)
to find the corresponding index (include<iterator>
first).See http://codepad.org/XQTx0vql for the complete code.