Search code examples
c++arrayssfml

How do I make an array of Vector2f from SFML?


I don't know how to make an array with Vector2f from SFML. It only works partially, it only works for the last variable returned.

Vector2f apple()
{
    Vector2f s(2,4);
    Vector2f f(2,4);
    return s,f;
};

s would be equal to 0,0 and f would be normal.


Solution

  • In C++, you're not able to return multiple values from a function like you're trying to do here:

    return s,f;
    

    There's many ways you could return multiple objects from a function:

    std::make_pair

    You could utilise std::make_pair to return both Vector2f's, like so:

    std::pair<Vector2f, Vector2f> apple() {
        Vector2f s(2, 4);
        Vector2f f(2, 4);
        return std::make_pair(s, f);
    }
    

    Now, you can retrieve both values by doing:

    std::pair<Vector2f, Vector2f> result = apple();
    Vector2f s = result.first;
    Vector2f f = result.second;
    

    std::vector

    You can use std::vector (or std::array) to return multiple objects.

    std::vector<Vector2f> apple() {
        Vector2f s(2, 4);
        Vector2f f(2, 4);
        return {s, f};
    }
    

    You can retrieve both of them doing:

    std::vector<Vector2f> result = apple();
    Vector2f s = result[0];
    Vector2f f = result[1];
    

    You could also use output parameters to hold the Vector2f result, but I'm sure the above two are sufficient in what you're trying to do.

    This post here also covers your question: Returning multiple values from a C++ function