Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiler error with C++ std::vector of array

the following code doesn't compile with gcc 4.7.0 (using std=c++11 -O3)

int n;
std::vector< int[4] > A;
A.resize(n);

the error message is length, but eventually

functional cast to array type ‘_ValueType {aka int[4]}‘

Is this correct? or should this compile? And more importantly, how to avoid this problem? (without defining a new struct to hold the int[4])

EDIT:

how to solve the problem with C++98?

like image 788
Walter Avatar asked Aug 29 '12 19:08

Walter


3 Answers

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.

You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x:

std::vector<std::array<type, size> >

(You'll want to replace std::array with std::tr1::array to use the template included in C++ TR1, or boost::array to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)

@source By:James McNellis

So the code would look like:

int n;
std::vector<std::array<int,3>> A;
A.resize(n);
like image 125
heretolearn Avatar answered Nov 11 '22 01:11

heretolearn


without defining a new struct to hold the int[4]

Impossible. You have to either define or find a struct (std::array, std::tr1::array, boost::array). Else, this code will never compile.

like image 4
Puppy Avatar answered Nov 11 '22 02:11

Puppy


See 23.1/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.

Thus in C++03 vector requires the contained items to be copy constructable, which C-style arrays are not. The error message is correct and the code should fail to compile. Just use a vector of vectors, a struct to wrap your array, or vector of std::array in C++11.

Note that I believe the copy-constructable restriction is lifted container-wide in C++11 and I'm not sure if/how you could store C-style arrays within one or if it's prohibited more explicitly.

like image 2
Mark B Avatar answered Nov 11 '22 02:11

Mark B