A function that always returns the same vector

I am trying to write a utility function that will return a vector. The returned vector will always have the same entries. I use it to filter the enum ( Directions

) so that clients can get the subset they want.

Here's an example of how I hope to approach the problem:

std::vector<Directions> horizontalDirections()
{
    static std::vector<Directions> toReturn;
    if (toReturn.size() == 0)
    {
        toReturn.push_back(Left);
        toReturn.push_back(Right);
    } 
    return toReturn;
}

      

Can this be done correctly?

+3


source to share


3 answers


How do you do it. But I would return the link const

so that it doesn't escape the copy if needed:

const std::vector<Directions>& horizontalDirections();

      

Also, if you are using C ++ 11, your implementation can be shortened as:



const std::vector<Directions>& horizontalDirections()
{
    static std::vector<Directions> toReturn({Left, Right});
    return toReturn;
}

      

If you're using C ++ 11, you can go even further and declare as horizontalDirections

global const vector

instead of a function:

const std::vector<Directions> horizontalDirections({Left, Right});

      

+8


source


This is basically the correct idea. I would return with a link to avoid copying the vector. And you can make the body more readable with the C ++ 11 initializer style:



const std::vector<Directions>& horizontalDirections() {
    static const std::vector<Directions> toReturn = {
        Left,
        Right
    };
    return toReturn;
}

      

+5


source


I wouldn't do it as a function at all, but as a constant like this in the global scope:

const std::vector<Direction> horizentalDirections = {Left, Right};

      

for which constants are made.

0


source







All Articles