Home >Backend Development >C++ >How Can I Efficiently Compare a Variable to Multiple Values in C ?
Comparing Variables to Multiple Values Efficiently
In certain scenarios, it becomes necessary to compare a variable against several options simultaneously. Typically, developers reach for the OR operator; however, this approach often leads to complications.
The Ideal Solution
Ideally, we seek a convenient method to distinguish between multiple groups, as exemplified by the following code:
if (num = (1,2,3)) else if (num = (4,5,6)) else if (num = (7,8,9))
C 11 Solution Using std::initializer_list
In C 11, std::initializer_list can be employed to achieve the desired functionality. By defining a is_in template function, we can efficiently compare a variable to a set of options:
#include <algorithm> #include <initializer_list> template <typename T> bool is_in(const T& v, std::initializer_list<T> lst) { return std::find(std::begin(lst), std::end(lst), v) != std::end(lst); }
This allows us to perform comparisons succinctly:
if (is_in(num, {1, 2, 3})) { DO STUFF }
C 17 Solution: More Efficient
C 17 introduced a highly optimized solution that works well with any type:
template<typename First, typename ... T> bool is_in(First &&first, T && ... t) { return ((first == t) || ...); } // ... // s1, s2, s3, s4 are strings. if (is_in(s1, s2, s3, s4)) // ...
This version generates efficient code even for complex types like strings, unlike the C 11 counterpart.
The above is the detailed content of How Can I Efficiently Compare a Variable to Multiple Values in C ?. For more information, please follow other related articles on the PHP Chinese website!