如何在不循环的情况下将数组的内容复制到 C++ 中的 std::vector?

2021-12-21 00:00:00 复制 vector c++ stl

我有一个值数组,它从程序的不同部分传递给我的函数,我需要存储这些值以供以后处理.由于我不知道在处理数据之前我的函数会被调用多少次,我需要一个动态存储结构,所以我选择了一个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 and array size, you can just say:

std::vector<ValueType> vec(a, a + n);

...假设 a 是您的数组,而 n 是它包含的元素数.否则,std::copy() w/resize() 会起作用.

...assuming a is your array and 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 循环――这只是你是否必须在代码中看到它的问题.O(n) 运行时性能对于复制值是不可避免的.

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().

相关文章