Friday, April 1, 2016

Min, Max, argMin, argMax of std::vector in c++

I love c++.  I hate c++. I can confirm that c++ exists.  There... that's how I feel.  Coming from basic to VB to Matlab to Fortran to python to c++ - and all within the realm of numerical analysis - I view c++ as that dumb guy who thinks he's so much smarter than everyone else.  The rest of us just have to deal with him because he...is...always...there... but nobody really respects him (Linux: I'm talking to you too even though I have grown quite fond of you as my daily OS).

Anyway...ya ya ya c++ writes operating systems.  Beat that Fortran.  At least if I want to find the minimum and maximum values of an array, it's simple in Matlab and Fortran and Python and ... mrp min(x), max(x), argmin(x), argmax(x) or something simple like that.

Stackexchange is a godsend...not so much for this question though.

Here is how to do it in c++ using c++ BS to do it.

I almost exclusively use std::vectors so that's what I'm talking about now.

double min = *std::min_element(x.begin(), x.end());
double max = *std::max_element(x.begin(), x.end());

int argMin = std::distance(x.begin(), std::min_element(x.begin(), x.end()));
int argMax = std::distance(x.begin(), std::max_element(x.begin(), x.end()));

1 comment:

Unknown said...

Helped me very much. Thanks!