如何優(yōu)雅地實現(xiàn)判斷一個值是否在一個集合中?
作者:守望先生
如何判斷某變量是否在某個集合中?注意,這里的集合可能并不是指確定的常量,也可能是變量。
本文轉載自公眾號“編程珠璣”(ID:shouwangxiansheng)。
如何判斷某變量是否在某個集合中?注意,這里的集合可能并不是指確定的常量,也可能是變量。
版本0
- #include <iostream>
- int main(){
- int a = 5;
- if(a == 1 || a == 2 || a == 3 || a == 4 || a == 5){
- std::cout<<"find it"<<std::endl;
- }
- return 0;
- }
常規(guī)做法,小集合的時候比較方便,觀感不佳。
版本1
- #include <iostream>
- #include <set>
- int main(){
- int a = 5;
- std::set<int> con_set = {1, 2, 3, 4, 5};
- if(con_set.find(a) != con_set.end()){
- std::cout<<"find it"<<std::endl;
- }
- return 0;
- }
不夠通用;不是常數(shù)的情況下,還要臨時創(chuàng)建set,性能不夠,性價比不高。當然通用一點你還可以這樣寫:
- std::set<decltype(a)> con_set = {1, 2, 3, 4, 5};
版本2
- #include <iostream>
- // 單參
- template <typename T>
- inline bool IsContains(const T& target) {
- return false;
- }
- template <typename T, typename... Args>
- inline bool IsContains(const T& target, const T& cmp_target, const Args&... args) {
- if (target == cmp_target)
- return true;
- else
- return IsContains(target, args...);
- }
- int main(){
- int a = 6;
- if(IsContains(a,1,2,3,4,5)){
- std::cout<<"find it"<<std::endl;
- }
- return 0;
- }
模板,通用做法。
版本3
需要C++17支持:,涉及的特性叫做fold expression,可參考:
https://en.cppreference.com/w/cpp/language/fold
- #include <iostream>
- template <typename T, typename... Args>
- inline bool IsContains(const T& target, const Args&... args) {
- return (... || (target == args));
- }
- int main(){
- int a = 5;
- if(IsContains(a,1,2,3,4,5)){
- std::cout<<"find it"<<std::endl;
- }
- return 0;
- }
責任編輯:趙寧寧
來源:
編程珠璣