Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...