I have TArray with custom structure in, that contains another structures and variables. No need for me to compare all elements one by one.
I need to get the answer: are they equal or not.
TArray<FItemAttribute> ItemAttributes
FItemAttribute is a structure.
I need to do next check
if (Stack->ItemAttributes != ItemAttributes)
It does’n work.
Next options do not work also
if (Stack->ItemAttributes.operator!=(ItemAttributes))
if (ItemAttributes.operator!=(Stack->ItemAttributes))
I can’t use const with my structure
const TArray<FItemAttribute> ItemAttributes
It gives error.
Please suggest the fast way how to do it.
Thanks in advance.
Could you give more information, please. TArray does support comparison, if your element type supports comparison, i.e. you need to have defined an operator== and operator!= overload for your FItemAttributes struct.
I have TArray. It contains structure - FItemAttribute. Structure contains custom ENum and bool variables.
Two TArrays are created. I have to get an answer: Is it one array? Or one of them contains different variables.
Even if one of bool variables contains true in the first array and false in the second, the TArrays are different.
If one array contains another ENum variable, the TArrays are different.
If one array has more elements that another one, even if all other elements are totally simular, the TArrays are different.
And if arrays have the same number of elements, with the same variables, with the same sequence, they are equal.
I can check it in loop one by one till the first difference.
However, I believe, there is a better way.
struct FItemAttribute
{
ESomeEnum Enum;
bool Bool;
// You need to write this for your type to be comparable
friend bool operator==(const FItemAttribute& Lhs, const FItemAttribute& Rhs)
{
return Lhs.Enum == Rhs.Enum && Lhs.Bool == Rhs.Bool;
}
};
And then you have two arrays like this:
TArray<FItemAttribute> Array1 = { { ESomeEnum::Val1, true }, { ESomeEnum::Val2, false } };
TArray<FItemAttribute> Array2 = Array1; // Array2 is a copy of Array1
… then you can compare them:
check(Array1 == Array2); // check the arrays are the same
If you then change one of the arrays, say to make it a different length, they will no longer be the equal:
Array2.Pop();
check(Array1 != Array2); // check the arrays are different
If we add an element back into the array so that they’re the same length again, but we add a different value (e.g. by the Bool field having a different value), then the arrays will still be different:
Array2.Add(FItemAttribute{ ESomeEnum::Val2, true });
check(Array1 != Array2); // check the arrays are still different
If we set the Bool field of that new element to false, then the arrays become equal again:
Array2.Last().Bool = false;
check(Array1 == Array2); // check that the arrays are now the same again