日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何優(yōu)雅地實(shí)現(xiàn)判斷一個值是否在一個集合中?

本文轉(zhuǎn)載自公眾號“編程珠璣”(ID:shouwangxiansheng)。

如何判斷某變量是否在某個集合中?注意,這里的集合可能并不是指確定的常量,也可能是變量。

版本0

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

常規(guī)做法,小集合的時候比較方便,觀感不佳。

版本1

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

不夠通用;不是常數(shù)的情況下,還要臨時創(chuàng)建set,性能不夠,性價比不高。當(dāng)然通用一點(diǎn)你還可以這樣寫:

 
 
 
  1. std::set con_set = {1, 2, 3, 4, 5}; 

版本2

 
 
 
  1. #include  
  2. // 單參 
  3. template  
  4. inline bool IsContains(const T& target) { 
  5.   return false; 
  6.  
  7. template  
  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"<
  17.     } 
  18.     return 0; 

模板,通用做法。

版本3

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

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

 
 
 
  1. #include  
  2. template  
  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"<
  9.     } 
  10.     return 0; 

網(wǎng)站名稱:如何優(yōu)雅地實(shí)現(xiàn)判斷一個值是否在一個集合中?
URL分享:http://m.5511xx.com/article/dhgoepp.html