Jump to content
  • Advertisement
Sign in to follow this  
floatingwoods

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

This topic is 2191 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


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

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

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

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

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!