Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a vector before main() in C++

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?

like image 557
R S Avatar asked Apr 25 '09 11:04

R S


3 Answers

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).

like image 57
dirkgently Avatar answered Sep 23 '22 06:09

dirkgently


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());
like image 31
Macke Avatar answered Sep 26 '22 06:09

Macke


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...

like image 38
Steve Jessop Avatar answered Sep 26 '22 06:09

Steve Jessop