如何判断某变量是否在某个集合中?注意,这里的集合可能并不是指确定的常量,也可能是变量。
版本0
#include
int main(){int a = 5;if(a == 1 || a == 2 || a == 3 || a == 4 || a == 5){std::cout<<"find it"<<std::endl;}return 0;
}
常规做法,小集合的时候比较方便,观感不佳。
版本1
#include
#include
int main(){int a = 5;std::set<int> con_set = {1, 2, 3, 4, 5}; if(con_set.find(a) != con_set.end()){std::cout<<"find it"<<std::endl;}return 0;
}
不够通用;不是常数的情况下,还要临时创建set,性能不够,性价比不高。当然通用一点你还可以这样写:
std::set<decltype(a)> con_set = {1, 2, 3, 4, 5};
版本2
#include
// 单参
template <typename T>
inline bool IsContains(const T& target) {return false;
}template <typename T, typename... Args>
inline bool IsContains(const T& target, const T& cmp_target, const Args&... args) {if (target == cmp_target)return true;elsereturn IsContains(target, args...);
}
int main(){int a = 6;if(IsContains(a,1,2,3,4,5)){std::cout<<"find it"<<std::endl;}return 0;
}
模板,通用做法。
版本3
需要C 17支持:,涉及的特性叫做fold expression,可参考:
#include
template <typename T, typename... Args>
inline bool IsContains(const T& target, const Args&... args) {return (... || (target == args));
}
int main(){int a = 5;if(IsContains(a,1,2,3,4,5)){std::cout<<"find it"<<std::endl;}return 0;
}
总结
我反正是学废了。你还有什么好的方法?
声明:
本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。