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:
templatebool is_in(const T& v, std::initializer_list 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:
templatebool 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3