一个总是返回相同向量的函数

A function that always returns the same vector

本文关键字:向量 函数 返回 一个      更新时间:2023-10-16

我试图写一个实用程序函数,将返回一个向量。返回的向量总是有相同的元素。我使用它来过滤枚举(Directions),以便客户端可以获得所需的子集。

下面是我希望如何处理这个问题的一个例子:

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

这是正确的方法吗?

你的工作方式。但是我将返回一个const引用,以便在不需要时可以避免复制:

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

同样,如果你使用c++ 11,你的实现可以缩写为:

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

如果使用c++ 11,您可以更进一步,将horizontalDirections声明为全局const vector而不是函数:

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

这基本上是正确的想法。我将通过引用返回以避免复制向量。你还可以使用c++ 11的初始化列表样式来使代码体更清晰:

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

我根本不会把它作为一个函数,而是作为一个全局范围内的常量:

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

就是常量的作用