0

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*[] ?

1
  • Yes it is. What have you tried ? It's simply a matter of allocating memory and then using 2 for loops and iterate through both vectors. Commented Oct 20, 2012 at 19:51

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

Why wouldn't you use std::vector for target?
@avakar you are correct, you should use std::vector for target aswell
Watch the edge case - if any of the inner vectors is empty then &*source[i].begin() has undefined behavior. But since the function takes float** quite likely it expects rectangular data, and so hopefully that's what the questioner has.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.