繁体   English   中英

c ++ stl复制功能适当的内存管理

[英]c++ stl copy function proper memory management

仅在以下代码上,我需要为floatArray分配带有new的内存,还是复制功能会为我分配内存?

这样将常数向量复制到数组中也可以吗? 为什么?

vector<float> floatVector;
//filled floatVector here

float *floatArray = new float[floatVector.size()];
copy(floatVector.begin(),floatVector.end(),floatArray);          
delete[] floatArray;

std::copy不分配内存,您应该自己做。

如果您不想先分配数组,则可以使用back_inserter迭代器将元素一一推送到某些容器中。 对于某些容器,这效率较低(我认为),但有时可能非常方便。

#include<iterator>
#include<vector>
#include<deque>

std::vector<float> floatVector(10,1.0);
std::deque<float>  floatDeque; //memory not allocated

//insert elements of vector into deque.
std::copy(floatVector.begin(), floatVector.end(), std::back_inserter(floatDeque));

复制不会为您分配,所以是的,您需要分配它。

std :: copy通过使用参数赋值(“ =”)运算符或参数copy构造函数进行复制(这可能与实现有关,我现在不确定)。 它什么也没做,只是遍历从param.begin()到param.end()的范围,并执行以下操作:

while (first!=last) *result++ = *first++;

因此,您需要自己分配必要的内存。 否则会产生不确定的行为。

这样可以将常数向量复制到数组吗? 取决于您要做什么。 通常,这很好,因为值是通过值而不是通过引用转移到目标的,因此不会破坏const正确性。

例如,这可以正常工作:

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
const std::vector<int> constvec(vec);

int *arrray = new int[2];
std::copy(constvec.begin(),constvec.end(),arrray);

复制函数从不分配内存,但是您必须为静态数据结构分配内存,但是对于动态数据结构,它将自动分配内存。

而且这个过程不好,但是最好使用另一个向量而不是那个floatarray

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM