日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

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

新聞中心

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

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

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

版本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ī)做法,小集合的時(shí)候比較方便,觀感不佳。

版本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ù)的情況下,還要臨時(shí)創(chuàng)建set,性能不夠,性?xún)r(jià)比不高。當(dāng)然通用一點(diǎn)你還可以這樣寫(xiě):

 
 
 
  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; 

分享標(biāo)題:如何優(yōu)雅地實(shí)現(xiàn)判斷一個(gè)值是否在一個(gè)集合中?
URL鏈接:http://www.dlmjj.cn/article/dhgoepp.html