-4

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
  • 1
  • 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

1 Answers1

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
  • 100
  • 6
  • 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