一个总是返回相同向量的函数
A function that always returns the same vector
我试图写一个实用程序函数,将返回一个向量。返回的向量总是有相同的元素。我使用它来过滤枚举(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};
就是常量的作用
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用向量的template_back函数
- 如何删除除 ArduinoSTL 的向量函数之外的所有函数
- 在使用标准向量函数时引发'std::bad_alloc'实例后调用的终止
- 我可以为向量函数返回 NULL<double> 吗?
- 将多个向量(函数结果)组合到一个使用模板中
- 如何在 c++ 中制作通用字符串到向量函数
- 为什么简单的C++向量函数会产生越界的下标
- 为什么我的向量函数的返回值总是 1
- 模板化向量函数参数的std::is_base_of
- 我的程序没有运行,多维向量函数
- C 如何使2D向量函数
- 如何从 v8 返回向量<T> C++ 函数
- C++ 如何使此向量函数接受任何分隔符
- 我想返回一个向量函数,<Competition>但被告知竞争是未声明的,并且我正在使用未定义的类'std::vector'
- C++:如何在类中使用向量函数
- 自己的"Insert"方法(向量)函数模板
- c++中的内存泄漏:循环中的向量函数
- 如何添加一个元素到一个向量函数
- 向量函数'at'