当前位置:主页 > 查看内容

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

发布时间:2021-08-02 00:00| 位朋友查看

简介:本文转载自公众号编程珠玑(ID:shouwangxiansheng)。 如何判断某变量是否在某个集合中?注意,这里的集合可能并不是指确定的常量,也可能是变量。 版本0 #include iostream intmain(){ int a = 5 ; if( a ==1|| a ==2|| a ==3|| a ==4|| a ==5){ std::cout fi……

本文转载自公众号“编程珠玑”(ID:shouwangxiansheng)。

如何判断某变量是否在某个集合中?注意,这里的集合可能并不是指确定的常量,也可能是变量。

版本0

  1. #include <iostream> 
  2. int main(){ 
  3.     int a = 5
  4.     if(a == 1 || a == 2 || a == 3 || a == 4 || a == 5){ 
  5.         std::cout<<"find it"<<std::endl
  6.     } 
  7.     return 0; 

常规做法,小集合的时候比较方便,观感不佳。

版本1

  1. #include <iostream> 
  2. #include <set> 
  3. int main(){ 
  4.     int a = 5
  5.     std::set<int> con_set = {1, 2, 3, 4, 5};  
  6.     if(con_set.find(a) != con_set.end()){ 
  7.         std::cout<<"find it"<<std::endl
  8.     } 
  9.     return 0; 

不够通用;不是常数的情况下,还要临时创建set,性能不够,性价比不高。当然通用一点你还可以这样写:

  1. std::set<decltype(a)> con_set = {1, 2, 3, 4, 5}; 

版本2

  1. #include <iostream> 
  2. // 单参 
  3. template <typename T> 
  4. inline bool IsContains(const T& target) { 
  5.   return false; 
  6.  
  7. template <typename T, typename... Args> 
  8. inline bool IsContains(const T& target, const T& cmp_target, const Args&... args) { 
  9.   if (target == cmp_target) 
  10.     return true; 
  11.   else 
  12.     return IsContains(target, args...); 
  13. int main(){ 
  14.     int a = 6
  15.     if(IsContains(a,1,2,3,4,5)){ 
  16.         std::cout<<"find it"<<std::endl
  17.     } 
  18.     return 0; 

模板,通用做法。

版本3

需要C++17支持:,涉及的特性叫做fold expression,可参考:

https://en.cppreference.com/w/cpp/language/fold

  1. #include <iostream> 
  2. template <typename T, typename... Args> 
  3. inline bool IsContains(const T& target, const Args&... args) { 
  4.     return (... || (target == args)); 
  5. int main(){ 
  6.     int a = 5
  7.     if(IsContains(a,1,2,3,4,5)){ 
  8.         std::cout<<"find it"<<std::endl
  9.     } 
  10.     return 0; 

本文转载自网络,原文链接:http://mp.weixin.qq.com/s?__biz=MzI2OTA3NTk3Ng==&mid=2649286475&idx=1&sn=c8bf3e969da462f658812523768d6d55&chksm=f2f9942cc58e1d3aa4862fb92d700bab31bd995c3102c521b12acb7c349807dc7b6c3d18d656&mpshare=1&s
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐