C++ 将向量的内容复制到数组中的最快方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12866912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to copy the contents of a vector into an array?
提问by Steve Barna
Possible Duplicate:
How to convert vector to array C++
可能的重复:
如何将向量转换为数组 C++
When working with arrays you have the ability to use
使用数组时,您可以使用
memcpy( void *destination, const void *source, size_t num );
However vectors simply provide iterators for a copy method, rendering memcpy useless. What is the fastest method for copying the contents a vector to another location?
然而,向量只是为复制方法提供迭代器,使 memcpy 无用。将矢量内容复制到另一个位置的最快方法是什么?
回答by Konrad Rudolph
std::copy
, hands down. It's heavily optimised to use the best available method internally. It's thus completely on par with memcpy
. There is no reason ever to use memcpy
, even when copying between C-style arrays or memory buffers.
std::copy
, 把手放下。它经过大量优化以在内部使用最佳可用方法。因此它完全与memcpy
. 没有理由使用memcpy
,即使在 C 样式数组或内存缓冲区之间复制时也是如此。
回答by Rob?
You'll have to measure that for yourself, in your environment, with your program. Any other answer will have too many caveats.
您必须在您的环境中使用您的程序为您自己测量。任何其他答案都会有太多警告。
While you do that, here is onemethod you can compare against:
当你这样做时,这里有一种你可以比较的方法:
std::copy(source.begin(), source.end(), destination);
回答by Rahul Tripathi
Try this:-
尝试这个:-
std::vector<int> newvector(oldvector);
For copying in an array try this:-
要在数组中复制,请尝试以下操作:-
std::copy(source.begin(), source.end(), destination);
回答by mathematician1975
You can use memcpy with a vector - vectors are guaranteed to be contiguous in memory so provided that the vector is not empty, you can use &vData[0]
(where vData
is your vector) as your source pointer to memcpy
您可以将 memcpy 与向量一起使用 - 向量保证在内存中是连续的,因此只要向量不为空,您就可以使用&vData[0]
(vData
您的向量在哪里)作为指向的源指针memcpy
EDITAs mentioned by comments to other answers, this only works if the vector's value_type is trivially copyable.
编辑正如对其他答案的评论所提到的,这仅在向量的 value_type 可简单复制时才有效。