"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Compare a Variable Against Multiple Values in C++?

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

Posted on 2025-03-13
Browse:785

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

template
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.

Latest tutorial More>

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