orion elenzil
orion elenzil

Reputation: 5433

c++ - cast vector<T> to vector<array<T>>

I have a std::vector of a simple datatype, and would like to convert it in O(1) to a std::vector of std::arrays of the same simple datatype.

In particular both forms represent an array of all the vertex indices of a triangle mesh. They both contain exactly the same number of indices, in exactly the same order, they just have different notions of boundaries.

So eg,

std::vector<uint32_t> X;
std::vector<std::array<uint32_t, 3>> = < ??? > (X);

Upvotes: 1

Views: 168

Answers (1)

Jan15
Jan15

Reputation: 539

std::vector is not the right tool for this. std::vector is owning, thus if you want to reinterpret the memory allocated by X as a "vector" of arrays of ints, you should use a non-owning container such as std::span. Even then, you would have to use reinterpret_cast, which is recommended to avoid whenever possible. Such as:

std::span<std::array<uint32_t, 3>> points (reinterpret_cast<std::array<uint32_t, 3>*>(
    X.data()), X.size()/3);

Beware though, depending on the number of values in the std::array that you cast into, you might get into issues because of padding: consecutive arrays don't have to touch each other in memory.

For all of these reasons, I would instead recommend to either iterate over each third element or provide a wrapper class around X, which encapsulates the strong semantic bond between the owned data and the view on it. That's also because the view is now ephemeral: it has to be recreated whenever X reallocates.

Upvotes: 2

Related Questions