Most efficient way to compare a variable to multiple values?

Here’s a way in C++11, using std::initializer_list:

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

with that, you can do:

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

It is not very efficient though when not used with built-in types. int will work fine, but if you compare std::string variables for example, the produced code is just awful.

In C++17 however, you can instead use a much more efficient 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)) // ...

The C++11 version would be very inefficient here, while this version should produce the same code as hand-written comparisons.

Leave a Comment