memcpy和vector的搭配使用

有时需要把其他类型的数据(torch::Tensor)转成vector。
1.例子

void tensor2Vect(torch::Tensor& box, vector<float>& boxvect)
{
    std::vector<float>boxvect_new(box.numel(),-1);//[1]
    box = box.to(torch::kCPU);//[2]
    std::memcpy(&boxvect_new[0], box.data_ptr(),box.numel()*sizeof(float ));//[3]
    boxvect = boxvect_new;
 }

总结:
(1) 当使用未初始化大小的vector时,使用memcpy时,被拷贝的对象里面存在动态内存。比如:vector对象大小无法确定,memcpy不管这事直接拷贝sizeof大小的内存,导致vector的内存结构破坏,vector析构时就出错了。因此memcpy和vector的搭配使用时,首先一定要给vector初始化大小,如[1]处实例;
(2) 记得把torch::Tensor转成CPU,如[2]处;
(3) memcpy的第一个参数如果是vector,则不能写成memcpy(&vector,应该写 memcpy(&vector[0],因为&vector[0]是取第一个元素的地址,vector不同于数组,不能用名字代替首地址。
(4) tensor---->vector,直接使用for循环push_back比使用std::memcpy耗时:
----pushback time: 0.096139ms, memcpy time:0.013888ms
----pushback time: 0.099949ms, memcpy time:0.014745ms
----pushback time: 0.097549ms, memcpy time:0.014277ms
----pushback time: 0.105581ms, memcpy time:0.013891ms
----pushback time: 0.097005ms, memcpy time:0.014123ms
----pushback time: 0.104942ms, memcpy time:0.014149ms
----pushback time: 0.096715ms, memcpy time:0.014039ms
----pushback time: 0.10761ms, memcpy time:0.013313ms
----pushback time: 0.102769ms, memcpy time:0.015343ms

你可能感兴趣的:(c&c++,libtorch)