Limit integer to bounds [duplicate]

北慕城南 提交于 2019-12-01 08:49:29

问题


I'm trying to make sure that int x is greater or equal than 0 but smaller than 1080 (screen size in this case).

I came up with this

int x = 123;
x = std::min(std::max(x, 0), 1080);

This seems ugly. Is there a better way to achieve this?


回答1:


If you live in the future, you can use std::clamp from C++17:

x = std::clamp(x, 0, 1080);



回答2:


Naive solution looks ok too:

int x = 123;
if (x < 0)
    x = 0;
if (x > 1080)
    x = 1080;

or wrap everything in a function:

template<typename T>
T between(const T x, const T min, const T max){
   if (x < min)
       return min;

   if (x > max)
       return max;

   return x;
}

int x = between(123, 0, 1080);



回答3:


Use an unsigned as the type for x. That automatically constrains it to be non-negative.

Then you're left with just the call to std::min which is palatable to me at least.

Building a class that takes an int on construction and has a conversion operator to int is also plausible but requires a fair bit of boilerplate.




回答4:


Why not just do something like this?

int x = 123; /* Or some arbitrary number */
bool bIsInRange = (x >= 0) && (x < 1080);
if(!bIsInRange){
   std::cout << "Variable 'x' is not between 0 and 1080." << std::endl;
   return 1;
} // else, x is fine. Continue operations as normal.


来源:https://stackoverflow.com/questions/41535581/limit-integer-to-bounds

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