How to cheaply assign C-style array to std::vector?

*爱你&永不变心* 提交于 2020-01-09 05:04:26

问题


Currently I do the following:

// float *c_array = new float[1024];

void Foo::foo(float *c_array, size_t c_array_size) {
  //std::vector<float> cpp_array;

  cpp_array.assign(c_array, c_array + c_array_size);
  delete [] c_array;
}

How can I optimize this assigning? I would like not to perform elementwise copy but just swap pointers.


回答1:


The current std::vector doesn't provide any capability or interface to take ownership of previously allocated storage. Presumably it would be too easy to pass a stack address in by accident, allowing more problems than it solved.

If you want to avoid copying into a vector, you'll either need to use vectors through your entire call chain, or do it the C way with float[] the entire time. You can't mix them. You can guaranteed that &vec[0] will be equivalent to the C-array though, fully contiguous, so using vector in the whole program may be feasible.




回答2:


Currently, the std::vector interface does not possess the capacity to move from or swap with anything except another std::vector.




回答3:


The only way to do it would be to create a custom allocator.

  1. Write an allocator class that you can initialise with your array.

  2. Instantiate the vector with the allocator as an argument.




回答4:


Unlikely it's possible - it's quite dangerous, because std::vector doesn't know how the memory was allocated and how it should be freed.

If it's possible, you may replace original allocation with creation of std::vector of correct size. It uses contiguous memory area, so it can replace manually allocated buffer.



来源:https://stackoverflow.com/questions/5836324/how-to-cheaply-assign-c-style-array-to-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!