如何廉价地将 C 样式数组分配给 std::vector? [英] How to cheaply assign C-style array to std::vector?
问题描述
目前我执行以下操作:
//float *c_array = new float[1024];void Foo::foo(float *c_array, size_t c_array_size) {//std::vectorcpp_array;cpp_array.assign(c_array, c_array + c_array_size);删除 [] c_array;}
我怎样才能优化这个分配?我不想执行元素复制,而只是交换指针.
当前的 std::vector
不提供任何功能或接口来获取先前分配的存储的所有权.据推测,意外传递堆栈地址太容易了,导致问题多于解决的问题.
如果您想避免复制到向量中,您要么需要在整个调用链中使用向量,要么始终使用 float[]
以 C 方式进行.你不能混合它们.你可以保证 &vec[0]
将等同于 C 数组,但完全连续,所以在整个程序中使用向量可能是可行的.>
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. 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.
这篇关于如何廉价地将 C 样式数组分配给 std::vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!