静态向量的初始化
我想知道是否有比下面更好的初始化静态向量的方法?
class Foo
{
static std::vector<int> MyVector;
Foo()
{
if (MyVector.empty())
{
MyVector.push_back(4);
MyVector.push_back(17);
MyVector.push_back(20);
}
}
}
这是一个示例代码:)
Push_back() 中的值是独立声明的;不在数组或其他东西中。
编辑:如果不可能,也告诉我:)
I wonder if there is the "nicer" way of initialising a static vector than below?
class Foo
{
static std::vector<int> MyVector;
Foo()
{
if (MyVector.empty())
{
MyVector.push_back(4);
MyVector.push_back(17);
MyVector.push_back(20);
}
}
}
It's an example code :)
The values in push_back() are declared independly; not in array or something.
Edit: if it isn't possible, tell me that also :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 C++03 中,最简单的方法是使用工厂函数:
“返回值优化”应该意味着数组被填充到位,而不是复制(如果这是一个问题)。或者,您可以从数组初始化:
如果您不介意使用非标准库,则可以使用 Boost.Assignment:
在 C++11 或更高版本中,您可以使用大括号初始化:
In C++03, the easiest way was to use a factory function:
"Return value optimisation" should mean that the array is filled in place, and not copied, if that is a concern. Alternatively, you could initialise from an array:
If you don't mind using a non-standard library, you can use Boost.Assignment:
In C++11 or later, you can use brace-initialisation:
使用 C++11:
With C++11:
通常,我有一个用于构建我使用的容器的类(例如 这个来自 boost 的),这样你就可以这样做:
这样,你也可以将 static const 化,以避免意外修改。
对于静态,您可以在 .cc 文件中定义它:
在 C++Ox 中,我们将有一个语言机制来使用初始值设定项列表来执行此操作,因此您可以这样做:
请参阅 此处。
Typically, I have a class for constructing containers that I use (like this one from boost), such that you can do:
That way, you can make the static const as well, to avoid accidental modifications.
For a static, you could define this in the .cc file:
In C++Ox, we'll have a language mechanism to do this, using initializer lists, so you could just do:
See here.
你可以尝试这个:
但它可能只有当你有一个很长的向量时才值得,而且它看起来也好不了多少。但是,您可以摆脱重复的 Push_back() 调用。当然,如果您的值“不在数组中”,您必须先将它们放入其中,但是您可以根据上下文静态地执行此操作(或至少是引用/指针)。
You could try this one:
But it's probably only worth when you have a really long vector, and it doesn't look much nicer, either. However, you get rid of the repeated push_back() calls. Of course, if your values are "not in an array" you'd have to put them into there first, but you'd be able to do that statically (or at least references/pointers), depending on the context.
使用静态对象进行初始化怎么样?在它的构造函数中
可以调用对象中的静态函数来进行初始化。
How about initializing using a static object. In its constuctor it
could call a static function in the object to do the initalization.
对于 boost,您可以使用 boost::assign 命名空间中定义的 +=() 运算符。
或使用静态初始化:
或者更好的是,如果您的编译器支持 C++ 11,请使用初始化列表。
with boost you can use the +=() operator defined in the boost::assign namespace.
or with static initialization:
or even better, if your compiler supports C++ 11, use initialization lists.