Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you store arithmetic operators in an array i,e(+, -, *, /) in C++

Tags:

c++

I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because 3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.

Edit:

Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.

like image 943
Amr Ahmed Avatar asked Oct 19 '18 22:10

Amr Ahmed


1 Answers

You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.

int add(int a, int b) {
    return a + b;
}

int sub(int a, int b) {
    return a - b;
}

int mul(int a, int b) {
    return a * b;
}

int div(int a, int b) {
    return a / b;
}

typedef int (*funptr)(int, int);

funptr arr[] = { add, sub, mul, div };

You can then call them like:

(arr[1])(2, 1)   // call sub(2, 1)

The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.

like image 134
CoffeeTableEspresso Avatar answered Nov 13 '22 00:11

CoffeeTableEspresso