How to initialize a vector in C++

Md Faisal picture Md Faisal · Jan 18, 2012 · Viewed 654.3k times · Source

I want to initialize a vector like we do in case of an array.

Example

int vv[2] = {12, 43};

But when I do it like this,

vector<int> v(2) = {34, 23};

OR

vector<int> v(2);
v = {0, 9};

it gives an error:

expected primary-expression before ‘{’ token

AND

error: expected ‘,’ or ‘;’ before ‘=’ token

respectively.

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Jan 18, 2012

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));