Reputation: 7221
I am implementing a 3 dimensional array. Much like cells and sheets of an Excel document. x and y being the page size and z being the number of sheets. For now the x and y indices can be the same for every page.
I thought to approach this with vectors (let's for now just say for strings only), but declaring it as follows:
std::vector<std::string> sheets;
//x and y being the x-y coordinates and z being the number of pages.
int size = x*y*z;
sheets.reserve(size);
Thus giving me a nice contiguous piece of memory (as is definition of a std::vector), which is fast and efficient.
My question is: Is there a way of doing this with std::array? Is there a way that to create the array size when the object is created, or must this be know at compile time?
class sheetsObj
{
int x, y, z;
int size;
//Where size is x * y * z.
std::array<std::string, size> sheets;
public:
sheetsObj(int xInd, int yInd, int zInd) : x{ xInd }, y{ yInd }, z{ zInd } {};
....
}
Thanks in advance.
Upvotes: 0
Views: 162
Reputation: 3172
std::array
has its size fixed by a template parameter, thus evaluated at compile time and probably not suitable for your needs (unless all the sheets are designed to have the same size forever?).
A std::vector
will perfectly meet your requirements, since the resizing overhead is not used by your program, and you will get your memory block as needed.
std::dynarray
would probably be the best class for you to use, since it represents a runtime initializable array which remains fixed-sized during his lifetime. However, initially scheduled to be released with the C++14 standard, a vote has been cast to exclude it from the upcoming standard, leaving it to be proposed later into a separate Technical Specification.
Upvotes: 1
Reputation: 65600
The best rule of thumb is to use std::vector
when you can, std::array
when you have to. In this case, std::vector
is the best option for you. As you say, the size of std::array
must be known at compile-time, so this is a no-brainer if you need dynamically-sized storage.
Upvotes: 2