Efficient ways to compare a variable with multiple values

In this article, we will discuss the ways to compare a variable with values.

Method 1: The idea is to compare each variable individually to all the multiple values at a time.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to compare one variable
// with multiple variable
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel using || operator
 
    // Check for vowel
    if (character == ('a' || 'e'
                      || 'i' || 'o'
                      || 'u')) {
        cout << "Vowel";
    }
 
    // Otherwise Consonant
    else {
        cout << "Consonant";
    }
 
    return 0;
}
chevron_right

Output
Consonant

Explanation:
The above code gives the Wrong Answer as comparing variable in the above way is incorrect and it forced to code in the below way:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to compare one variable
// with multiple variable
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel individually
 
    // Check for vowel
    if (character == 'a'
        || character == 'e'
        || character == 'i'
        || character == 'o'
        || character == 'u') {
        cout << "Vowel";
    }
 
    // Otherwise Consonant
    else {
        cout << "Consonant";
    }
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to compare
// one variable with multiple
// variable
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
  // Variable to be compared
  char character = 'a';
 
  // Compare the given variable
  // with vowel using || operator
 
  // Check for vowel
  if (character == 'a' || character == 'e' ||
      character == 'i' || character == 'o' ||
      character == 'u')
  {
    System.out.print("Vowel");
  }
 
  // Otherwise Consonant
  else
  {
    System.out.print("Consonant");
  }
}
}
 
// This code is contributed by 29AjayKumar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to compare
# one variable with multiple
# variable
 
# Driver Code
if __name__ == '__main__':
   
    # Variable to be compared
    character = 'a';
 
    # Compare the given variable
    # with vowel using or operator
 
    # Check for vowel
    if (character == 'a' or
        character == 'e' or
        character == 'i' or
        character == 'o' or
        character == 'u'):
        print("Vowel");
 
    # Otherwise Consonant
    else:
        print("Consonant");
 
# This code contributed by Princi Singh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to compare
// one variable with multiple
// variable
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
  // Variable to be compared
  char character = 'a';
 
  // Compare the given variable
  // with vowel using || operator
 
  // Check for vowel
  if (character == 'a' || character == 'e' ||
      character == 'i' || character == 'o' ||
      character == 'u')
  {
    Console.Write("Vowel");
  }
 
  // Otherwise Consonant
  else
  {
    Console.Write("Consonant");
  }
}
}
 
// This code is contributed by gauravrajput1
chevron_right

Output
Vowel

Method 2 – using Bitmasking: Another approach is to check among multiple groups of values and then create a bitmask of the values and then check for that bit to be set.

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to compare a value
// with multiple values
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Create bitmasks
    unsigned group_1 = (1 << 1) | (1 << 2) | (1 << 3);
    unsigned group_2 = (1 << 4) | (1 << 5) | (1 << 6);
    unsigned group_3 = (1 << 7) | (1 << 8) | (1 << 9);
 
    // Values to be checked
    int value_to_check = 9;
 
    // Checking with created bitmask
    if ((1 << value_to_check)
        & group_1) {
        cout << "found a match in group 1";
    }
    if ((1 << value_to_check)
        & group_2) {
        cout << "found a match in group 2";
    }
    if ((1 << value_to_check)
        & group_3) {
        cout << "found a match in group 3";
    }
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to compare a value
// with multiple values
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // Create bitmasks
    int group_1 = (1 << 1) |
                  (1 << 2) | (1 << 3);
    int group_2 = (1 << 4) |
                  (1 << 5) | (1 << 6);
    int group_3 = (1 << 7) |
                  (1 << 8) | (1 << 9);
 
    // Values to be checked
    int value_to_check = 9;
 
    // Checking with created bitmask
    if (((1 << value_to_check) &
          group_1) > 0)
    {
        System.out.print("found a match " +
                         "in group 1");
    }
    if (((1 << value_to_check) &
          group_2) > 0)
    {
        System.out.print("found a match " +
                         "in group 2");
    }
    if (((1 << value_to_check) &
          group_3) > 0)
    {
        System.out.print("found a match " +
                         "in group 3");
    }
}
}
 
// This code is contributed by shikhasingrajput
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to compare a value
// with multiple values
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
  // Create bitmasks
  int group_1 = (1 << 1) |
                (1 << 2) |
                (1 << 3);
  int group_2 = (1 << 4) |
                (1 << 5) |
                (1 << 6);
  int group_3 = (1 << 7) |
                (1 << 8) |
                (1 << 9);
 
  // Values to be checked
  int value_to_check = 9;
 
  // Checking with created
  // bitmask
  if (((1 << value_to_check) &
        group_1) > 0)
  {
    Console.Write("found a match " +
                  "in group 1");
  }
  if (((1 << value_to_check) &
        group_2) > 0)
  {
    Console.Write("found a match " +
                  "in group 2");
  }
  if (((1 << value_to_check) &
        group_3) > 0)
  {
    Console.Write("found a match " +
                  "in group 3");
  }
}
}
 
// This code is contributed by gauravrajput1
chevron_right

Output
found a match in group 3

Note: This approach works best for values that don’t exceed the natural size of your CPU. It would typically be 64 in modern times. The general solution to this problem using Template from C++11. Below is the program for the same:

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for comparing variable
// with multiples variable
#include <algorithm>
#include <initializer_list>
#include <iostream>
using namespace std;
 
template <typename T>
 
// Function that checks given variable
// v in the list lst[]
bool is_in(const T& v,
           std::initializer_list<T> lst)
{
    return (std::find(std::begin(lst),
                      std::end(lst), v)
            != std::end(lst));
}
 
// Driver Code
int main()
{
    // Number to be compared
    int num = 10;
 
    // Compare with multiple variables
    if (is_in(num, { 1, 2, 3 }))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    // Character to be compared
    char c = 'a';
 
    // Compare with multiple variables
    if (is_in(c, { 'x', 'a', 'c' }))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    return 0;
}
chevron_right

Output
Not in group
Found in group

Note: It is not very efficient though when not used with primitive types. For std::string it will produce an error. This task became really easy with C++17, as it comes with Fold Expression. This is generally called Folding which helps to express the same idea with less code and it works well with any data type. Here, “||” operator to reduce all the Boolean results to a single one which is only False if all the comparison results False. Below is the program for the same:

Program 4:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for comparing variable
// with multiple variables
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <string>
using namespace std;
 
template <typename First, typename... T>
 
// Function that checks given variable
// first in the list t[]
bool is_in(First&& first, T&&... t)
{
    return ((first == t) || ...);
}
 
// Driver Code
int main()
{
    // Number to be compared
    int num = 10;
 
    // Compare using template
    if (is_in(num, 1, 2, 3))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    // String to be compared
    string c = "abc";
 
    // Compare using template
    if (is_in(c, "xyz", "bhy", "abc"))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    return 0;
}
chevron_right

Output: 
 

 

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :