Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

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*&)’
like image 936
WoooHaaaa Avatar asked Jun 15 '12 03:06

WoooHaaaa


People also ask

How do you push an array into a vector?

If you want to push the data into vector of vectors, you have to write something like this: vector<int> inner; vector< vector<int> >outer; ... outer. pushback(inner);

Can you push an array in C?

It is not possible to 'push' in a statically allocated classic C-style array and it would not be a good idea to implement your own 'method' to dynamically reallocate an array, this has been done for you in the STL, you can use vector : #include <vector> // ...

Can I store an array in a vector?

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.


1 Answers

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.

like image 74
Jesse Good Avatar answered Oct 04 '22 14:10

Jesse Good