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.
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.
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.
To get the datatype of variable, use typeid(x). name() of typeinfo library. It returns the type name of the variable as a string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With