STL函数测试一个值是否在某个范围内?
我有一个函数:bool inBounds(int value, int low, int high)
。是否有一个等效的 STL 可以做有用的事情(特别是采用不同类型的变量)?我用谷歌找不到,我宁愿重用而不是重写。
I have a function: bool inBounds(int value, int low, int high)
. Is there an STL equivalent that does useful things (takes variables of different types, specifically)? I can't find one using Google, and I'd prefer to re-use rather than re-write.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++17 中,没有与此类函数直接等效的函数,但对于具有快速相等比较的较小类型,您可以使用
std::clamp
:或者,您可以编写自己的函数来测试这一点:
这会检查
value
是否在范围[低,高)。如果您想要范围 [low, high],则可以将其写为注意这是如何纯粹根据
operator <
定义的,这意味着任何仅支持operator
operator
的类; 可以在这里使用。
同样,这是使用自定义比较器的一个:
后一个比较器有一个很好的优点,即
low
和high
不必与value
具有相同的类型>,只要比较器可以处理它就可以正常工作。希望这有帮助!
In C++17, there's no direct equivalent of a function like this, but for smaller types with fast equality comparisons you could use
std::clamp
:Alternatively, you can just write your own function to test for this:
This checks if
value
is in the range [low, high). If you want the range [low, high], you'd write this asNote how this is defined purely in terms of
operator <
, which means that any class that supports justoperator <
can be used here.Similarly, here's one using custom comparators:
This latter one has the nice advantage that
low
andhigh
don't have to be the same type asvalue
, and as long as the comparator can handle that it will work just fine.Hope this helps!
有一个小缺点,您必须记住哪个参数在哪里。
我不可能是唯一一个在一段时间后返回代码时完全理性的参数排序令人困惑的人。
您可以加倍努力并定义
然后您可以更明确地表达您的意思:
如果处于抽象模式,那么概括以适应不同的包含/排除组合并不难。
当然,这对于您的目的来说可能有点过分了。
YMMV,等等。
has the slight drawback that you have to remember which parameter goes where.
I can't be the only one whose perfectly rational parameter ordering is bewildering when returning to code after some time.
You could go the extra mile and define
Then you can be more explicit about what you mean:
If one is in abstraction mode it's not too hard to generalise to accomodate different inclusive/exclusive combinations.
Of course this might be overkill for your purposes.
YMMV, and all that.
您可以使用
std::less
、std::more
、std::bind
和std::compose
编写一个code>,但这确实有点过分了。Lambda 要简单得多:
[](int value, int low, int high){return !(value < low) && (value < high);}
或者,如果 low 和 high 在范围内
[low, high](int value){return !(value < low) && (值<高)};
You could compose one from
std::less
,std::more
,std::bind
andstd::compose
, but that's truly overkill.Lambda's are far easier:
[](int value, int low, int high){return !(value < low) && (value < high);}
or, if low and high are in scope
[low, high](int value){return !(value < low) && (value < high)};
我几乎认为你最好不要尝试用整个函数来完成这样一个看似微不足道的任务,而只是内联行为。
像这样的事情:
如果您有理由不这样简单地编写代码,请告诉我,我可以提供更复杂的答案。
I'd almost think you'd be better off not attempt such a seemingly trivial task with a whole function and just inline the behavior.
Something like this:
If you have a reason for not writing the code simply like this, please let me know and I can provide a more sophisticated answer.