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

99封情书 提交于 2019-11-30 07:08:40

问题


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*&)’

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


Just use

vector<int*>  .That will definitely work.

A relevant discussion on the same topic : Pushing an array into a vector




回答6:


To instantiate the vector, you need to supply a type, but int[2] is not a type, it's a declaration.



来源:https://stackoverflow.com/questions/11044304/can-i-push-an-array-of-int-to-a-c-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!