Can i push an array of int to a C++ vector?

WoooHaaaa picture WoooHaaaa · Jun 15, 2012 · Viewed 37.1k times · Source

Is there any problem with my code ?

std::vector<int[2]> weights;
int weight[2] = {1,2};
weights.push_back(weight);

It can't be compiled, please help to explain why:

no matching function for call to ‘std::vector<int [2], std::allocator<int [2]> >::push_back(int*&)’

Answer

Jesse Good picture Jesse Good · Jun 15, 2012

The reason arrays cannot be used in STL containers is because it requires the type to be copy constructible and assignable (also move constructible in c++11). For example, you cannot do the following with arrays:

int a[10];
int b[10];
a = b; // Will not work!

Because arrays do not satisfy the requirements, they cannot be used. However, if you really need to use an array (which probably is not the case), you can add it as a member of a class like so:

struct A { int weight[2];};
std::vector<A> v;

However, it probably would be better if you used an std::vector or std::array.