[英]How to cheaply assign C-style array to std::vector?
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.我不想执行元素复制,而只是交换指针。
The current std::vector
doesn't provide any capability or interface to take ownership of previously allocated storage.当前的std::vector
不提供任何功能或接口来获取先前分配的存储的所有权。 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.如果您想避免复制到向量中,则需要在整个调用链中使用向量,或者始终使用float[]
以 C 方式执行此操作。 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.您可以保证&vec[0]
将等效于 C 数组,完全连续,因此在整个程序中使用向量可能是可行的。
Currently, the std::vector
interface does not possess the capacity to move from or swap with anything except another std::vector
.目前, std::vector
接口不具备移动或交换除另一个std::vector
之外的任何东西的能力。
The only way to do it would be to create a custom allocator.唯一的方法是创建一个自定义分配器。
Write an allocator class that you can initialise with your array.编写一个分配器 class ,您可以使用您的数组对其进行初始化。
Instantiate the vector with the allocator as an argument.使用分配器作为参数实例化向量。
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.不太可能 - 这是非常危险的,因为 std::vector 不知道 memory 是如何分配的以及应该如何释放它。
If it's possible, you may replace original allocation with creation of std::vector of correct size.如果可能,您可以用创建正确大小的 std::vector 来替换原始分配。 It uses contiguous memory area, so it can replace manually allocated buffer.它使用连续的 memory 区域,因此可以替换手动分配的缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.