简体   繁体   中英

Efficient initialization of a std::vector

A std::vector contains a buffer of continuous memory internally for a given type, with the exception of bools. Is there anyway of constructing a vector by specifying this buffer such that no coping of data is required?

I have a C api which gives me a buffer of data of a certain type. I would like to be able to manipulate this data via the functionality associated with std::vector, such as std::vector<>::iterator, begin(), end() etc.

Maybe you have a better suggestion as to how I might work with these buffers, as they are huge and I don't wish to copy them.

The api allocates the memory and provides a function which I call to tell it to release it again.

Why dont you just wrap the buffer in a simple class containing the functions you want to be able to use. Something like this will probably suffice, using the fact that pointers are iterators.

template<typename T>
struct RawBuffer<T>
{
  RawBuffer( T* in_buffer, size_t in_n ) : buffer(in_buffer), n(in_n) {}
  T* buffer;
  size_t n;
  T* begin() { return buffer; }
  T* end() { return buffer+n; }
  const T* begin() const { return buffer; }
  cont T* end() const { return buffer+n; }
  T& operator[](size_t i) { return buffer[i]; }
  const T& operator[](size_t i) const { return buffer[i]; }
};

Now you can use it kinda like a vector:

RawBuffer<MyObject> values( generate_objects(n), n );

//Set an entry
values[1] = MyObject()

//Or use an entry
values[1].do_something();

//Lets use some std functions on the object.
std::for_each( values.begin(), values.end(), my_object_fn );

//Or create a real vector from it
std::vector<MyObject> values_copy( values.begin(), values.end() );

If you also want to manage the memory that the buffer contains then you'll need to add a destrtuctor and remove the default copy constructor and assignment operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM