initialising a static std::vector data member

D

Dylan

what is the best way of initializing a static std::vector data member
with some values?

(currently I just push_back some values in the constructor if the size
== 0)

thanks
 
R

Rolf Magnus

Dylan said:
what is the best way of initializing a static std::vector data member
with some values?

By static, you mean static member? You can initialize it with an array.

#include <vector>
#include <iostream>

struct Foo
{
static std::vector<int> vec;
private:
static const int array[];
};

const int Foo::array[] = { 1, 10, 100, 1000, 10000, 42 };
std::vector<int> Foo::vec(array, array + sizeof(array)/sizeof(*array));

int main()
{
std::cout << Foo::vec.back() << '\n';
}

If your vector is also constant, you might just as well use the array
directly instead.
 
D

Dylan

thanks Rolf

Dylan said:
what is the best way of initializing a static std::vector data member
with some values?

By static, you mean static member? You can initialize it with an array.

#include <vector>
#include <iostream>

struct Foo
{
static std::vector<int> vec;
private:
static const int array[];
};

const int Foo::array[] = { 1, 10, 100, 1000, 10000, 42 };
std::vector<int> Foo::vec(array, array + sizeof(array)/sizeof(*array));

int main()
{
std::cout << Foo::vec.back() << '\n';
}

If your vector is also constant, you might just as well use the array
directly instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top