本文转载自公众号“编程珠玑”(ID:shouwangxiansheng)。
如何判断某变量是否在某个集合中?注意,这里的集合可能并不是指确定的常量,也可能是变量。
版本0
- #include <iostream>
- 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 <iostream>
- #include <set>
- 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 <iostream>
- // 单参
- 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;
- else
- return 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,可参考:
https://en.cppreference.com/w/cpp/language/fold
- #include <iostream>
- 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;
- }
最近,DevOps的采用导致了企业计算的重大转变。除无服务器计算,动态配置和即付...
2020年对于云计算行业来说是突破性的一年,因为公共云供应商增加了收入,而疫情...
本文转载自网络,原文链接:https://mp.weixin.qq.com/s/vlOUg46B5bcmToX-fjavJQ...
中国最?好的一朵云飘进了华瑞银行。阿里云将进一步助力华瑞银行All in Cloud。 -...
9月17日,2020云栖大会上,阿里云正式发布工业大脑3.0。 阿里云智能资深产品专家...
很长时间没有更新原创文章了,但是还一直在思考和沉淀当中,后面公众号会更频繁...
查看表结构,sbtest1有主键、k_1二级索引、i_c二级索引 CREATE TABLE `sbtest1` ...
在TOP云(zuntop.com)科技租赁过服务器的站长都知道独立服务器在价格上比VPS主...
定义 this是函数运行时自动生成的内部对象,即调用函数的那个对象。(不一定很准...
一、PostgreSQL行业位置 一 行业位置 首先我们看一看RDS PostgreSQL在整个行业当...