C++: select argmax over vector of classes w.r.t. arbitrary expression
Posted
by
karpathy
on Stack Overflow
See other posts from Stack Overflow
or by karpathy
Published on 2011-02-22T23:19:00Z
Indexed on
2011/02/22
23:24 UTC
Read the original article
Hit count: 264
Hello, 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
.
What makes it even more complicated is that even the name of the vector changes. Sometimes it's vec
, sometimes it can be something else. I have many vectors that contain A
's. This could be changed if this makes the problem too hard.
Is there some nice way to avoid this insanity in C++? What's the neatest way to handle this?
Thank you!
© Stack Overflow or respective owner