Sign in to follow this  
Followers 0
floatingwoods

How to initialize std::vector with array data without internal copy operation

7 posts in this topic

Hello,

I have an array of float data, say:

const float myArray[5]={1.0f,2.0f,3.0f,4.0f,5.0f};

I now want to "connect" that data to following vector:

const std::vector<float> myVector

I don't want any data to be copied internally. Can I do that?

Thanks!
0

Share this post


Link to post
Share on other sites
An [i]std::vector[/i] assumes ownership of the data and cannot be used to refer to an external buffer. Why do you need the array as an [i]std::vector[/i] if you already have it in the array?
3

Share this post


Link to post
Share on other sites
Thanks for the quick reply Brother Bob!

I have a collection of functions that expect const vectors as arguments. Instead of rewriting the interfaces for those functions, I thought it would be faster if I can "connect" the buffer to a vector and still use the same functions.

Cheers
0

Share this post


Link to post
Share on other sites
Is there a way to prevent the data from ever being an array, and just to create it in place in the vector? That way you can avoid copying.

If possible, functions should be templates written in terms of iterators rather than directly taking standard containers. This is flexible, because pointers are a type of iterator too. Edited by rip-off
3

Share this post


Link to post
Share on other sites
I think the Kosher way to do this is with a (very) custom allocator that just happens to always return the address of your array and blows-off the free. Edited by Shannon Barber
0

Share this post


Link to post
Share on other sites
Vector semantics require that it copy the objects you insert, regardless of how the allocator is implemented. And if you never insert anything, it would always appear/behave empty and not be of much use to anyone.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0