Reputation: 878
Okay, this may sound like a stupid question, but I haven't read anything from the documentation that says it is not possible. Either that, or I overlooked something again.
By multi-dimensional, I mean like arrays. Is something like
vector<vector<double>>
possible? What are the possible drawbacks, at least when compared to arrays?
Upvotes: 2
Views: 144
Reputation: 1143
What you're describing is absolutely possible, although if you aren't using a C++11 compiler you need to type it as:
vector<vector<double> >
The space between the two >
characters being necessary so that the compiler doesn't think you're using the >>
operator, as in:
cin >> x;
Of course, with a vector of vectors, you can add and remove elements, either at the top level where the elements are vectors, or at the second level where the elements are doubles. This can be a blessing, a curse, or both, depending on what you are trying to do - note that if you add a double to one of the second-level vectors, the length of that vector is different from all of the others. Because the second-level vectors can have different lengths, I would recommend against using them as a replacement for 2D arrays if fixed dimensions are what you want.
Upvotes: 0
Reputation:
It is possible.
One of the possible drawbacks could be that it might result in multiple separate allocations from the free store because each vector makes its own allocations. In contrast, a dynamic array allocation is made only once from contiguous memory which is more cache friendly.
Upvotes: 1
Reputation: 20992
It's possible, but note that you need a space between the two >
s to remove the ambiguity between the right shift operator, i.e.
vector<vector<double> >
Also, I wouldn't call those vectors arrays, since array has a very well-defined meaning in C++:
double matrix[10][10];
edit: As people pointed out, you don't need a space when using C++11.
Upvotes: 2