Convert values to values inside a range in c++ , optimized using boost or std

ⅰ亾dé卋堺 提交于 2019-12-07 08:14:24

问题


I want to validate all the elemnent of an array. If an element is under a value, swap by a min value and if it is above a value, swap by a max value.

But I don´t know how I can do it optimized. For do it I go above all elements, element by element but it is not optimized, and it spend a lot of cpu time in very large arrays.

This is an example of my code:

#include <iostream> 
#include <math.h>
const int MAX = 10;
int main ()
{
    float minVal = 2.0;
    float maxVal = 11.0;

    float vElem[] = {-111111.0/0.0, 10.0, 90.0, 8.0, -7.0,
                    -0.6, 5.0, 4.0, 33.0, 222222222.0/0};

    for(int i=0; i<MAX; i++){
            if(isinf(vElem[i])==-1 || vElem[i]<minVal) vElem[i] = minVal;
            if(isinf(vElem[i])==1 || vElem[i]>maxVal || isnan(vElem[i])) vElem[i] = maxVal;

            std::cout << vElem[i]<< std::endl;
    }
}

回答1:


I don't think using elaborate constructs would buy you much here. Maybe making your code a bit cleaner ?

std::for_each(std::begin(vElem), std::end(vElem), [](float &val) {
    val = clamp(val, minVal, maxVal);
});

this is what a typicall clamp function returns




回答2:


  for(int i=0; i<MAX; i++){
      float c = vElem[i];

      //Could convert c to an integer here, so the below uses integer operations
      //Additional cost is two multiplications (scaling up and scaling back down).

      float n = c + ((c < min) * (min - c)) + ((c > max) * (max - c));
      std::cout << n << std::endl;
  }
  • Two multiplications
  • Four additions
  • Two comparisons

I think this is faster than any of the clamp() implementations referred to in the other answer.



来源:https://stackoverflow.com/questions/23884149/convert-values-to-values-inside-a-range-in-c-optimized-using-boost-or-std

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!