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

Arrays aren't copy constructable so you can't store them in containers (vector in this case). You can store a nested vector or in C++11 a std::array.


You cant do that simply.

It's better you use either of these:

  1. vector <vector<int>> (it's basically a two dimensional vector.It should work in your case)

  2. vector< string > (string is an array of characters ,so you require a type cast later.It can be easily.).

  3. you can declare an structure (say S) having array of int type within it i.e.

    struct S{int a[num]} ,then declare vector of vector< S>

So indirectly, you are pushing array into a vector.


Array can be added to container like this too.

    int arr[] = {16,2,77,29};
    std::vector<int> myvec (arr, arr + sizeof(arr) / sizeof(int) );

Hope this helps someone.


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.

Tags:

C++

Stdvector