偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

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

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

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

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

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

  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; 

 

責(zé)任編輯:趙寧寧 來(lái)源: 編程珠璣
相關(guān)推薦

2020-02-05 14:05:21

Java技術(shù)數(shù)組

2018-12-14 09:32:06

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

2018-12-14 09:16:31

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

2020-12-11 11:19:54

區(qū)塊鏈資金投資

2020-10-14 06:18:20

Golang字符串數(shù)組

2020-08-24 08:07:32

Node.js文件函數(shù)

2022-06-21 14:44:38

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

2024-11-07 10:55:26

2024-11-08 15:56:36

2017-12-12 15:24:32

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

2025-01-26 09:35:45

2025-02-23 08:00:00

冪等性Java開(kāi)發(fā)

2023-08-01 08:54:02

接口冪等網(wǎng)絡(luò)

2020-08-17 08:20:16

iOSAOP框架

2024-01-26 12:35:25

JavaScript項(xiàng)目軟件包

2023-09-19 23:21:48

Python列表

2022-05-16 08:17:36

裝飾器模式

2018-12-29 08:15:28

Tomcat應(yīng)用部署

2017-10-10 14:41:38

Linux

2023-02-26 01:37:57

goORM代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)