将整数限制到范围 [英] Limit integer to bounds

查看:100
本文介绍了将整数限制到范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确保int x大于或等于0但小于1080(在这种情况下为屏幕尺寸).

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

我想到了这个

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

这看起来很丑.有没有更好的方法来实现这一目标?

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

推荐答案

如果您将来生活,可以使用 std::clamp来自C ++ 17 :

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

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

这篇关于将整数限制到范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆