Florin
Florin

Reputation: 2961

Convert from std::vector<std::vector<float>> to float**

There is a function which takes a float** parameter. I have the values in a variable of type std::vector<std::vector<float>>.

Is it possible to make such a conversion without allocating a temporary float*[] ?

Upvotes: 0

Views: 3806

Answers (3)

mauve
mauve

Reputation: 2016

This will work:

std::vector<std::vector<float>> source;

std::vector<float*> target(source.size());
for (int i = 0; i < source.size(); ++i)
  target[i] = &*source[i].begin();

As you see you do not need to copy the inner std::vector<>s but you need to recreate the outer. A std::vector<> guarantees linear storage of its members (meaning it is compatible with a C-array) so it works for the inner vectors.

Upvotes: 2

alestanis
alestanis

Reputation: 21863

You have to do the conversion by hand, by filling your float** with the values of vector<vector<float> > with two loops.

You will have to allocate the inner float* in any case.

Upvotes: 1

Thomas
Thomas

Reputation: 181715

Not directly, but you don't have to copy the data from the "inner" vectors. Instead, you can create an array of pointers to the data() attributes of each inner vector.

Upvotes: 4

Related Questions