c++ - Optimal way to choose less or greater operator before loop -
i have 2 arrays comprising x,y vales y=f(x). provide function finds value of x corresponds either min or max sampled value of y.
what efficient way select proper comparison operator before looping on values in arrays?
for example, following:
double findextremum(const double* x, const double* y, const unsigned int n, const bool ismin) { static std::less<double> lt; static std::greater<double> gt; std::binary_function<double,double,bool>& isbeyond = ismin ? lt : gt; double xm(*x), ym(*y); (unsigned int i=0; i<n; ++i, ++x, ++y) { if (isbeyond()(*y,ym)) { ym = *y; xm = *x; } } }
unfortunately, base class std::binary_function
not define virtual operator().
will compiler g++ 4.8 able optimize straight forward implementation?
double findextremum(const double* x, const double* y, const unsigned int n, const bool ismin) { double xm(*x), ym(*y); (unsigned int i=0; i<n; ++i, ++x, ++y) { if ( ( ismin && (*y<ym)) || (!ismin && (*y>ym)) ) { ym = *y; xm = *x; } } }
is there way arrange things make easy compiler optimize? there known algorithm doing this?
i prefer avoid using templated function, if possible.
you need pass comparison functor templated function parameter, e.g.
template <typename compare> double findextremum(const double* x, const double* y, const unsigned int n, compare compare) { double xm(*x), ym(*y); (unsigned int i=0; i<n; ++i, ++x, ++y) { if (compare(*y,ym)) { ym = *y; xm = *x; } } }
then if need runtime choice, write this:
if (ismin) { findextremum(x, y, n, std::less<double>()); } else { findextremum(x, y, n, std::greater<double>()); }
avoiding templated function not possible in case. best performing code 1 embeds comparison operation directly in loop, avoiding function call - can either write template or write 2 copies of function. templated function better solution.
Comments
Post a Comment