Comparing a Variable to Multiple Values Efficiently
Often in programming, it is necessary to check if a variable matches one of several options. This can be achieved through various methods, but it's essential to prioritize efficiency.
Inefficient Methods
Attempts to compare a variable to multiple values using logical operators like OR can lead to inefficient code. For example:
if (num == (1 || 2 || 3))
This approach evaluates each logical expression (1 || 2, 2 || 3) separately, which can result in wasted processing.
Efficient Solutions in C 11
One efficient solution in C 11 involves utilizing std::initializer_list. The following template function takes a variable and an initializer list of potential matches:
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); }
Now you can use it like:
if (is_in(num, {1, 2, 3})) { DO STUFF }
More Efficient Solution in C 17
C 17 introduces an even more efficient solution that works exceptionally well with any type:
template<typename First, typename ... T> bool is_in(First &&first, T && ... t) { return ((first == t) || ...); }
This template function uses perfect forwarding to evaluate each comparison efficiently, resulting in code that performs on par with hand-written comparisons.
The above is the detailed content of How Can I Efficiently Compare a Variable Against Multiple Values in C ?. For more information, please follow other related articles on the PHP Chinese website!