M
M
MaM2016-11-18 13:54:39
C++ / C#
MaM, 2016-11-18 13:54:39

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

2 answer(s)
A
Armenian Radio, 2016-11-18
@MaM

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

IDEONE
Performance - logarithmic of the number of elements. If the condition is checked many times, it makes sense to move set to a separate constant.

A
Adamos, 2016-11-18
@Adamos

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 question

Ask a Question

731 491 924 answers to any question