您现在的位置是:亿华云 > IT科技类资讯

如何优雅地实现判断一个值是否在一个集合中?

亿华云2025-10-03 06:35:24【IT科技类资讯】2人已围观

简介本文转载自公众号“编程珠玑”(ID:shouwangxiansheng)。如何判断某变量是否在某个集合中?注意,这里的集合可能并不是指确定的常量,也可能是变量。版本0#include<iostr

本文转载自公众号“编程珠玑”(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; } 源码库

很赞哦!(2)