Reputation: 1057
I'm having some trouble figuring the best way to represent this.
Initially I had a 2D vector of size N x N where each element were glm::vec2's. I initialized it like this:
//initialize vector
std::vector < std::vector < glm::vec2>> Gvectors;
//allocate space
Gvectors.resize(nGridCells + 1, std::vector<glm::vec2>(nGridCells + 1, glm::vec2(0.0f)));
//fill data
for (size_t i = 0; i < nGridCells+1; i++)
{
for (size_t j = 0; j < nGridCells+1; j++)
{
float dx = something;
float dx = something else;
Gvector[i][j] = glm::normalize( glm::vec2(dx, dy));
}
}
No I want multiple of these 2D vectors, with all different sizes. Each of them will have different sizes, typically in the range 10x10 to 100x100.
So I was thinking to make another nested vector, so it would be something like:
std::vector<std::vector <std::vector < std::vector < glm::vec2>>> Gvectors;
But when trying to figure out how to allocate the space using resize for a triple vector, I read that nested vectors can be troublesome for memory allocation and it can be often better to use standard arrays. But if I use arrays I think I get problems because I will have different sizes of each of my 2D arrays.
I guess what I'm asking, what is the best way to represent this. Basically a vector of 2D vectors or array of 2D arrays. I was also trying to make an array of 2D vectors, but would imagine that's not the best way to do it.
FYI, the sizes of the vectors will not change after initialization.
Thanks in advance!
Upvotes: 0
Views: 403
Reputation: 145429
Generally it's a good idea to name things.
Assuming you call your 2D vector e.g. Matrix, then
std::vector<Matrix> matrices;
is a reasonable way to expresses that the number of matrices, and their sizes and contents, can vary at run time.
If on the other hand you want to express that this information does not vary at run time after initialization, then use const
and add an initializer, like
std::vector<Matrix> const matrices = something;
How to define a class like Matrix
must surely be covered by a lot of SO questions, but simple searching didn't find it for me. It should really be in the SO C++ array FAQ, but answering it there would entail discussion of myriad details. So, in short, the most reasonable way is IMO
use a std::vector
for storage, and keep track of the matrix size,
define a non-public member function index_of
that provides the linear array index for a given row/col position, and
provide public member functions for access, like item
, at
, operator()
.
If instead you choose to define an operator[]
for access, and just let it return a pointer, then you don't need the index_of
and it can be more efficient, but you lose the ability to range check the column index, and you lose the general ability to put a break point on column indexing. So it's a less general, less reusable solution. Still, it's there as an option, and you can have both.
Upvotes: 1