std::vector of an array

2019-03-01 03:40发布

问题:

Following declaration passes compilation check:

int arr[3];
vector<int[3]> vec;  // ok !!

When trying to use vec practically as,

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.

What exactly goes wrong here ? Is such issue being addressed in C++11 ?

回答1:

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.



回答2:

The basic requirement of Standard library containers is that the elements should be Copy constructible and Assignable.

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]

Para 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.



回答3:

vectors, like any other containers, are unable to store arrays, for the same reasons that you can't assign an array to another array. You have a couple of alternatives:

  • The obvious one is to use an std::vector< std::vector<int> >.
  • If you want a more C++11 solution, you may find it better to have an std::vector of std::array. You would then have vec be of type std::vector< std::array<int, 3> > .