如何将数组的内容复制到C ++中的std :: vector而不循环? [英] How do you copy the contents of an array to a std::vector in C++ without looping?
问题描述
我有一个值数组,从程序的不同部分传递给我的函数,我需要存储以供后续处理。因为我不知道在处理数据之前我的函数将被调用多少次,我需要一个动态存储结构,所以我选择了一个std :: vector。我不想做标准循环push_back所有的值单独,这将是很好,如果我可以复制它使用类似于memcpy的东西。
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a std::vector. I don't want to have to do the standard loop to push_back all the values individually, it would be nice if I could just copy it all using something similar to memcpy.
推荐答案
如果你可以构造向量后,你已经得到数组&数组大小,您只需说:
If you can construct the vector after you've gotten the array & array size, you can just say:
std::vector<ValueType> vec(a, a + n);
...假设a是你的数组& n是它包含的元素的数量。否则,std :: copy()w / resize()将会执行。
...assuming a is your array & n is the number of elements it contains. Otherwise, std::copy() w/resize() will do the trick.
我会远离memcpy是普通数据(POD)类型。
I'd stay away from memcpy() unless you can be sure that the values are plain-old data (POD) types.
此外,值得注意的是,这些都没有真正避免for循环 - 这只是一个问题,它在你的代码或不。
Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.
最后,请注意,对于大多数STL算法,C风格数组是完全有效的容器 - 原始指针是等价于begin(),而(ptr + n)等效于end()。
Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to begin(), and (ptr + n) is equivalent to end().
这篇关于如何将数组的内容复制到C ++中的std :: vector而不循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!