4

For example:

#include<vector> using namespace std; int main() { vector<int[]> vec;//serious compiler error vector<int[2]> vec={{1,2}};//error:array must be initialized with a brace-enclosed initializer } 

In addition, how to rectify the grammar of the second one? I already use a brace-enclosed initializer.

2
  • 3
    The type you pass into a vector must be fixed at compile time. In an array, the size is part of the type. If you want something that is conceptually a "variable-length array", that is exactly what vector is for! Commented Oct 11, 2018 at 7:03
  • 2
    vector<array<int,2>> for the second one. Commented Oct 11, 2018 at 7:04

1 Answer 1

11

It's not a variable-length array, those do not exist in C++. It's an array without a size specifier, an incomplete type that doesn't meet the requirements of most (all?) vector operations.

The second attempt tries to copy c-arrays (list initialization always does copying), and that too is not supported.

If you want a vector of arrays, spell it as std::vector<std::array<int, 2>>.

Sign up to request clarification or add additional context in comments.

9 Comments

but vector<int[2]> vec; could be compiled without error. So vector<int[2]> vec; is OK but not support list initialization?
@bigxiao - Yes, because the default constructor of vector isn't instantiated with an operation that is illegal for c-arrays. Each vector c'tor is going to be different in that regard. You can't treat c-arrays as value types, they just aren't. That's what std::array exists for now.
@bigxiao You should read the next paragraph that says this depends on which operations are used on the vector.
@bigxiao - Not really that odd. resize is another member whose requirements a c-array does not meet.
@bigxiao - You can't. It's just not supported. That's not to say a vector of fixed sized arrays is not useful, but you need to use std::array for that, to make it a value type.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.