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 :)
How about initializing using a static object. In its constuctor it could call a static function in the object to do the initalization.
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:
With C++11:
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.
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.
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.