Answer the question
In order to leave comments, you need to log in
How to write an if statement for multiple conditions in a short and efficient way?
There is if(key == y || key == x || key ==h || key == g .....), I want to write something like this (k in {y,x,h,g} ). Or else how, in general, best practices. I thought about iterators, it's interesting to use them somehow in one line, but then the question of performance (whether gcc can) expand.
Answer the question
In order to leave comments, you need to log in
Something like this:
#include <set>
#include <iostream>
using namespace std;
int main()
{
const int alpha=301;
if(set<int>{0,200,300,400}.count(alpha))
{
cout << "found" << endl;
}
else
{
cout << "not found" << endl;
}
return 0;
}
Are you paid to save lines?
No matter how you write it (even if switch - case), there will still be comparisons and branches in machine code.
So don't bother stuffing it into iterators, but try to write it down so that it's readable at a glance - and it's impossible to make a typo that wouldn't be revealed by the same first glance.
By the way, it is also easier for the compiler to apply optimizations when the code is cumbersome, but primitive.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question