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
Susan SarandonOriginal
2024-12-29 13:19:14813browse

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))

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);
}

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 &amp;&amp;first, T &amp;&amp; ... 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!

Statement:
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