如何分配廉价C风格的数组到std :: vector的? [英] How to cheaply assign C-style array to std::vector?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/1733143/converting-between-c-stdvector-and-c-array-without-copying\">Converting C ++的std ::向量和C数组不复制之间
目前我做到以下几点:
// 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;
}
如何优化这一分配?我想不执行的elementwise副本,但只要将指针。
How can I optimize this assigning? I would like not to perform elementwise copy but just swap pointers.
推荐答案
目前的std ::矢量
不提供任何功能或接口取$ P的所有权$ pviously分配存储。 presumably那就太容易意外传递一个堆栈地址,允许更多的问题比它解决的。
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.
如果你想避免复制到一个载体,你要么需要通过你的整个调用链使用的载体,或者用做到这一点的C方式浮动[]
的整个时间。你无法将它们混合。您的 的可以保证&放大器; VEC [0]
将等同于C-阵列虽然完全连续的,在整个程序,以便使用矢量可能是可行的。
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屋!