My professor wants us to store a sequence of 2D points into this data member:
// Sequence of points.
std::array<Object, 2> *sequence_;
// Size of sequence.
size_t size_;
sequence_ is part of a class template called "points2d", where "Object" is supposed to be int, double, float, etc. Isn't sequence_ a pointer to an array with 2 elements only? I can see how it'll be able to store 1 2D point, but I can't see how it'll store several 2D points since "Object" isn't a pointer.
CodePudding user response:
In C , a pointer can point to a sequence of objects in memory. It is how we did containers before we had fancy classes like vector
and array
.
std::array<Object, 2> *sequence_;
points to the first std::array<Object, 2>
. There might be more in memory after the first one. It is a strange idea to use that in a teaching setup, because it is very confusing. The array has a compile-time length of 2, but the number of array depends on what you allocate.
So, if you do:
sequence_ = new std::array<Object, 2>[10];
you allocate ten arrays, each having two objects. You can then acces them with:
sequence_[4]; // fifth array of Object
sequence_[5][1]; // second Object of sixth array
You need to be careful to delete it with:
delete[] sequence_;
Most people on this SE would rather suggest:
std::vector<std::array<Object, 2>> sequence_;
or just
std::vector<Object> simple_sequence_;
CodePudding user response:
Isn't sequence_ a pointer to an array with 2 elements only?
It could be that, or it could be a pointer to an array of arrays. That is probably what's intended--to store the length of the outer array in size_
, and treat sequence_
as if it were:
std::array<Object, 2> sequence_[size_]; // not literally valid code
That is, sequence_
can be a pointer to the beginning of a 2D array, where one dimension is dynamic and the second dimension is 2.