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

Started by
6 comments, last by Shannon Barber 11 years, 4 months ago
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!
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?
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
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.
Thanks Rip-off!!

You are right, and I try to follow that way of doing nowadays. But my old code is a mess... ;)
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.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
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.
How about boost::array?
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement