[英]std::vector of an array
Following declaration passes compilation check: 以下声明通过编译检查:
int arr[3];
vector<int[3]> vec; // ok !!
When trying to use vec
practically as, 尝试将
vec
实际用作时,
vec.push_back(arr);
it results in many error like: 它导致许多错误,例如:
/usr/include/c++/4.6/ext/new_allocator.h:108:9: error: ISO C++ forbids initialization in array new [-fpermissive]
/usr/include/c++/4.6/bits/vector.tcc:314:4: error: invalid array assignment
/usr/include/c++/4.6/ext/new_allocator.h:118:30: error: request for member ‘~int [3]’ in ‘* __p’, which is of non-class type ‘int [3]’
Additionally, vec
doesn't push_back()
the int*
also. 另外,
vec
也不将int*
push_back()
。
What exactly goes wrong here ? 这里到底出了什么问题? Is such issue being addressed in C++11 ?
C ++ 11中是否解决了此类问题?
The basic requirement of Standard library containers is that the elements should be Copy constructible and Assignable . 标准库容器的基本要求是,元素应为Copy可构造和可分配的 。
Arrays are not assignable and hence the error, You cannot use them as Standard library container elements. 数组不可分配,因此会出现错误,您不能将它们用作标准库容器元素。
Reference: 参考:
C++03 Standard:23.1 Container requirements [lib.container.requirements] C ++ 03 Standard:23.1容器要求[lib.container.requirements]
Para 3: 第3段:
The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.
存储在这些组件中的对象的类型必须满足CopyConstructible类型(20.1.3)的要求以及Assignable类型的其他要求。
You can't store arrays in containers because they are neither assignable nor copyable, which are the requirements for all objects that are used with Standard Library containers. 您不能将数组存储在容器中,因为它们既不可分配也不可复制,这是与标准库容器一起使用的所有对象的要求。
The assignment operator is only attempted when you do push_back()
which is why your code compiles without it . 仅当您执行
push_back()
时才尝试使用赋值运算符,这就是为什么代码不使用它即可编译的原因 。
vector
s, like any other containers, are unable to store arrays, for the same reasons that you can't assign an array to another array. 与其他容器一样,
vector
s也无法存储数组,原因与您无法将数组分配给另一个数组的原因相同。 You have a couple of alternatives: 您有两种选择:
std::vector< std::vector<int> >
. std::vector< std::vector<int> >
。 std::vector
of std::array
. std::array
的std::vector
更好。 You would then have vec
be of type std::vector< std::array<int, 3> >
. vec
类型为std::vector< std::array<int, 3> >
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.