I want to be able to initialize a vector of a size 'SIZE' before main. Normally I would do
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
But the problem is that I would like to initialize the first item of the vector to be of a certain value, and the other to another value.
Is there an easy way to do this?
Try this:
static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init / sizeof init[ 0 ]);
Also, see std::generate
(if you want to initialize within a function).
Or just create a function and call that:
std::vector<int> init()
{
...
}
static std::vector<int> myvec = init()
A bit inefficient perhaps, but that might not matter to you now, and with C++0x and move it will be very fast.
If you want to avoid the copy (for C++03 and earlier), use a smart-pointer:
std::vector<int>* init() {
return new std::vector<int>(42);
}
static boost::scoped_ptr<std::vector<int>> myvec(init());
C++0x will allow initializer lists for standard containers, just like aggregates:
std::vector<int> bottles_of_beer_on_the_wall = {100, 99, 98, 97};
Obviously not standard yet, but it's allegedly supported from GCC 4.4. I can't find documentation for it in MSVC, but Herb Sutter has been saying their c++0x support is ahead of the committee...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With