Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most C++ way to check if value belongs to certain static set?

Let's say that I want to write something like this (the {1, 3, 7, 42, 69, 550123} set is known before compilation):

int x;
...
if (x == 1 || x == 3 || x == 7 || x == 42 || x == 69 || x == 5550123)
{
  ...
}

The condition looks ugly because we have 9 extra symbols ("|| x ==") for each possible value. How can I rewrite it in a more C++ way?

My best guess is:

int x;
...
const std::unordered_set<int> v = {1, 3, 7, 42, 69, 5550123};
if (v.count(x))
{
  ...
}

It has O(1) average complexity with some memory and time overhead, but still looks kinda ugly.

like image 574
Victor Avatar asked Jul 24 '18 10:07

Victor


People also ask

How do you check if an element exists in a set?

The standard solution to check for existence of an element in the set container ( std::set or std::unordered_set ) is to use its member function find() . If the specified element is found, an iterator to the element is returned; otherwise, an iterator to the end of the container is returned.

How do you check if number is in a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check what type a variable is in C++?

To get the datatype of variable, use typeid(x). name() of typeinfo library. It returns the type name of the variable as a string.


1 Answers

The only clean way to do this is to simply move it to a method. Name the method appropriately and it really does not matter what you do inside.

bool is_valid_foo_number(int x)
{
    return x == 1
        || x == 3
        || x == 7
        || x == 42
        || x == 69
        || x == 5550123;
}

The method looks good enough for me, because all I will ever see of it is

if (is_valid_foo_number(input))
{
    // ...
}

Should a technical detail change (like the sheer amount of valid numbers requiring another lookup approach or maybe a database instead of hardcoded values) you change the method's internals.

The point is that I think it only looks ugly... because you need to look at it while you look at your logic. You shouldn't have to look at the details anyway.

like image 126
nvoigt Avatar answered Oct 21 '22 15:10

nvoigt