自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何優(yōu)雅地實現(xiàn)判斷一個值是否在一個集合中?

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

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

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

[[373401]]

版本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; 

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

版本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; 

不夠通用;不是常數(shù)的情況下,還要臨時創(chuàng)建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; 

 

責任編輯:趙寧寧 來源: 編程珠璣
相關推薦

2020-02-05 14:05:21

Java技術數(shù)組

2018-12-14 09:16:31

裝載數(shù)據(jù)數(shù)組

2020-10-14 06:18:20

Golang字符串數(shù)組

2018-12-14 09:32:06

億級數(shù)據(jù)存在

2020-12-11 11:19:54

區(qū)塊鏈資金投資

2020-08-24 08:07:32

Node.js文件函數(shù)

2024-11-08 15:56:36

2022-06-21 14:44:38

接口數(shù)據(jù)脫敏

2024-11-07 10:55:26

2025-01-26 09:35:45

2017-12-12 15:24:32

Web Server單線程實現(xiàn)

2023-08-01 08:54:02

接口冪等網(wǎng)絡

2017-10-10 14:41:38

Linux

2018-12-29 08:15:28

Tomcat應用部署

2025-02-23 08:00:00

冪等性Java開發(fā)

2023-02-26 01:37:57

goORM代碼

2023-03-01 09:39:40

調度系統(tǒng)

2020-09-29 07:24:14

Python字典數(shù)據(jù)

2023-09-19 23:21:48

Python列表

2024-01-26 12:35:25

JavaScript項目軟件包
點贊
收藏

51CTO技術棧公眾號