user2445507
user2445507

Reputation: 453

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 am using it to filter an enum (Directions) so that clients can obtain the desired subset.

Here is 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;
}

Is this the correct way to go about it?

Upvotes: 3

Views: 117

Answers (3)

Arne
Arne

Reputation: 8511

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

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

that's what constants are made for.

Upvotes: 0

lvella
lvella

Reputation: 13481

The way you do it works. But I would return a const reference, so that a copy could be avoided if not needed:

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

Also, if you are using C++11, your implementation could be abbreviated as:

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

If using C++11, you could go even further and declare you horizontalDirections as a global const vector instead of a function:

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

Upvotes: 8

aschepler
aschepler

Reputation: 72431

That's basically the right idea. I would return by reference to avoid copying the vector. And you can make the body much more legible using a C++11 initializer-list style:

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

Upvotes: 5

Related Questions