Home > Mobile >  C Compare Vector3
C Compare Vector3

Time:03-01

Hello I am facing the following problem.

I have 3 coordinates vectors. For example, these look like this:

Vector3 vec1 = (100, 100, 100);
Vector3 vec2 = (150, 120, 110);
Vector3 vec3 = (-200, 120, 110);

Now I want to compare vec2 and vec3 with vec1 to find out which of the two vectors is closer to vec1 and then output a true or false.

As an example how the function could look like:

if (Vectorcompare(vec1, vec2, vec3))
{
    console.write("vec2 is nearer to vec1");
}
else
{
    console.write("vec3 is nearer to vec1");
}

//Output would be "vec2 is nearer to vec1"

Now I wonder how can I code the compare function?

It must be assumed that the coordinates can also go into the minus range, so a simple addition or subtraction could lead to wrong results.

CodePudding user response:

Look at the following code:

#include <iostream>
#include <vector>

class Vector3
{
public:

    int X, Y, Z;

    Vector3(int x, int y, int z) : X(x), Y(y), Z(z) {}
    ~Vector3() {}
};

double GetDistance(Vector3 vec1, Vector3 vec2)
{
    return std::sqrt(std::pow((vec1.X - vec2.X), 2)   std::pow((vec1.Y - vec2.Y), 2)   std::pow((vec1.Z - vec2.Z), 2));
}

int main()
{
    Vector3 vec1{ 100, 100, 100 };
    Vector3 vec2{ 150, 120, 110 };
    Vector3 vec3{ -200, 120, 110 };

    if (GetDistance(vec1, vec3) < GetDistance(vec2, vec3))
    {
        // vec1 is nearer to vec3
    }
    else
    {
        // vec2 is nearer to vec3
    }
}

Here in the above code, I have made a function GetDistance() that gets the distance between 2 vectors. Now in the main() function, you can just compare the distance between vec1 and vec3 with vec2 and vec3 and then do the desired action.

  • Related