Make sure all variables are equal to the same value in C ++

What is the easiest way to compare multiple variables to see if they are the same? For example, if var1 = 53, and I want to check if var2 or var3 is equal to equal var1 and to another? So far I have done this:

if(row1==row2==row3==row4==col1==col2==col3==col4==diag1==diag2)
    cout << "It is a magic square";
else
    cout << "Not a magic square";

However, this does not work. Thanks for the help.

+5
source share
6 answers

You cannot bind operators like that ==. You will need to write, for example.

if (row1==row2 && row2==row3 && row3==row4 && ...)
+3
source

In C ++ 11, you can use variable templates to define your own function:

#include <iostream>

template<typename T, typename U>
bool all_equal(T&& t, U&& u)
{
    return (t == u);
}

template<typename T, typename U, typename... Ts>
bool all_equal(T&& t, U&& u, Ts&&... args)
{
    return (t == u) && all_equal(u, std::forward<Ts>(args)...);
}

int main()
{
    int x = 42;
    int y = 42
    std::cout << all_equal(42, y, x);
}
+11
source

, == true false ( 1 0). , , - :

int vals[] = {row1,row2,row3,row4,col1,col2,col3,col4,diag1,diag2};
bool equals = true;
for (int i = 0; i < sizeof(vals); ++i) {
  if (vals[i] != vals[i+1]) {
    equals = false;
    break;
  }
}

, :

int val = vals[0];
for (int i = 1; i < sizeof(vals); ++i)
  val &= vals[i];
bool equals = val == vals[0];
+2

, , "==":

C , a == b == c; (==), . , a == b == c?

, (==), , , (==) .

a == b == c (a == b) == c, ., (a == b) == c ?

β€’ (a == b) 1 (true), 0 (false).

β€’ c (a == b).

, '==' .

+2
source

You will need to use && although this would increase the amount of code you need to enter. If you are comparing matrix values, I would suggest using a loop and indexes to compare values ​​instead of assigning them to variables and checking for equality.

if(row1==row2 && row2==row3 && row3==row4 && row4==col1 && col1==col2 && col2==col3 &&   col3==col4 && col4==diag1 && diag1==diag2)
    cout << "It is a magic square";
else
    cout << "Not a magic square";
0
source

Solution without any if

#include <iostream>

bool equals(int val1, int val2, int val3, int val4)
{
    return((val1 | val2 | val3 | val4) == (val1 & val2 & val3 & val4));
}

int main()
{
  std::cout << "1, 1, 1, 1 -> " << (equals(1, 1, 1, 1)?"true":"false") << std::endl;
  std::cout << "0, 0, 0, 0 -> " << (equals(0, 0, 0, 0)?"true":"false") << std::endl;
  std::cout << "0, 0, 1, 1 -> " << (equals(0, 0, 1, 1)?"true":"false") << std::endl;
  std::cout << "3, 3, 1, 1 -> " << (equals(3, 3, 1, 1)?"true":"false") << std::endl;
  std::cout << "-5, -5, -5, -5 -> " << (equals(-5, -5, -5, -5)?"true":"false") << std::endl;
  return(0);
}
0
source

All Articles