我可以把一个int数组到一个C ++向量? [英] Can i push an array of int to a C++ vector?

查看:110
本文介绍了我可以把一个int数组到一个C ++向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有问题吗?

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


推荐答案

数组不能在STL容器中使用的原因是因为它需要类型是可复制构造和可分配的(在c ++ 11中也可移动构造)。例如,您不能使用数组执行以下操作:

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;

但是,如果使用 std :: vector std :: array

这篇关于我可以把一个int数组到一个C ++向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆