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

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

Mary-Kate Olsen
Release: 2025-01-01 01:04:09
Original
342 people have browsed it

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

Comparing Variables to Multiple Values Efficiently

In certain scenarios, it becomes necessary to compare a variable against several options simultaneously. Typically, developers reach for the OR operator; however, this approach often leads to complications.

The Ideal Solution

Ideally, we seek a convenient method to distinguish between multiple groups, as exemplified by the following code:

if (num = (1,2,3))

else if (num = (4,5,6))

else if (num = (7,8,9))
Copy after login

C 11 Solution Using std::initializer_list

In C 11, std::initializer_list can be employed to achieve the desired functionality. By defining a is_in template function, we can efficiently compare a variable to a set of options:

#include <algorithm>
#include <initializer_list>

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

This allows us to perform comparisons succinctly:

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

C 17 Solution: More Efficient

C 17 introduced a highly optimized solution that works well with any type:

template<typename First, typename ... T>
bool is_in(First &&first, T && ... t)
{
    return ((first == t) || ...);
}

// ...

// s1, s2, s3, s4 are strings.
if (is_in(s1, s2, s3, s4)) // ...
Copy after login

This version generates efficient code even for complex types like strings, unlike the C 11 counterpart.

The above is the detailed content of How Can I Efficiently Compare a Variable to 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