有没有等效于Python的c++"in"关键字?

Is there an equivalent to Python's 'in' keyword for c++?

本文关键字:in 关键字 c++ Python 有没有      更新时间:2023-10-16

我试图更清晰、更紧凑地编写我的 c++ 代码,所以假设我试图避免这样的语句:

if(MIN_VALUE <= a && a <= MAX_VALUE)

并将其替换为类似于以下内容的内容:

if(a in [MIN_VALUE, MAX_VALUE])

您可以使用std::clamp,与大多数 STL 函数不同,它返回闭合区间[lo, hi]的值:

if (v == std::clamp(v, lo, hi)) {
    // lo <= v && v <= hi.
}

不,没有,但你可以自己构建一个:

template <typename T>
bool in(const T& a, const T& low, const T& high) 
{ 
    return a - low <= high - low; 
}