-3

I want to create an if code to check if variable x is a member of a defined group of constant named a, for example a = { 1 , 2 , 3 , 4 }, then use something like if (x != a).

I only know to use it like this if ( ( x != 1 ) || ( x != 2 ) || ( x != 3 ) || ( x != 4 ) )

tumble
  • 11
  • 2
  • Look into `std::set`. – HolyBlackCat Apr 29 '20 at 12:41
  • What resource are you using to learn C++? Not insulting you - just trying to figure out how best to direct you. – JohnFilleau Apr 29 '20 at 12:44
  • Does this answer your question? [How can I check if given int exists in array?](https://stackoverflow.com/questions/19299508/how-can-i-check-if-given-int-exists-in-array) – abcalphabet Apr 29 '20 at 12:46
  • If `x` is an integer type, `(x != 1) || (x != 2)` is always true, You probably mean `(x == 1) || (x == 2)` or it complement `(x != 1) && (x != 2)` – Jarod42 Apr 29 '20 at 13:00
  • Not the most efficient, but one-liner: `bool found = std::set{1, 2, 3, 4}.count(x);` – Jarod42 Apr 29 '20 at 13:05
  • Does this answer your question? [Optimize Conditions](https://stackoverflow.com/questions/61447353/optimize-conditions) – cigien Apr 29 '20 at 14:29

2 Answers2

0

You can use functions like this

bool exist_in_group(int value, const int* group,int group_size)
{
    bool res{false};
    for(int i=0;i<group_size;i++)
    {
        if(group[i] == value)
            res = true;
    }
    return res;
}

This function check if value exist in your array(group) or not

MH Alikhani
  • 110
  • 7
  • I'm aware of that method, but I wanted to ask if there are some default function available in C++ to save me some time to write out a new function myself. Thank you anyway! – tumble Apr 29 '20 at 15:08
  • you can use `std::find` instead – MH Alikhani Apr 30 '20 at 09:08
0

Had a similar issue. If the values are constant numbers you know at compile time, you could use a switch to check, then put that in an immediately imboked lambda to be able to call it as an expression:

if ( [](int x){
    switch(x){case 1: case 2: case 3: case 4: return true;}
    return false;}(x) ) {
  std::cout << "x is contained in group\n";
}

Could also use a function instead of a lambda, if you use it in many places and the group of numbers is fixed.

Kian
  • 1,654
  • 1
  • 14
  • 22