Home > Backend Development > C++ > How Can I Efficiently Compare a Variable Against Multiple Values in C ?

How Can I Efficiently Compare a Variable Against Multiple Values in C ?

Susan Sarandon
Release: 2024-12-29 13:19:14
Original
790 people have browsed it

How Can I Efficiently Compare a Variable Against Multiple Values in C  ?

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))
Copy after login

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&amp; v, std::initializer_list<T> lst)
{
    return std::find(std::begin(lst), std::end(lst), v) != std::end(lst);
}
Copy after login

Now you can use it like:

if (is_in(num, {1, 2, 3})) { DO STUFF }
Copy after login

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 &amp;&amp;first, T &amp;&amp; ... t)
{
    return ((first == t) || ...);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template