小编Bob*_*ugo的帖子

如何在C ++中将std :: vector移动到原始数组

如何std::vector安全地将其内容移动到数组中,而无需复制或遍历所有元素?

void someFunc(float* arr, std::size_t& size)
{
   std::vector<float> vec(5, 1.5f);
   // do something with the data

   size = vec.size();
   arr = vec.data(); // this doesn't work, as at the end of the function the data in std::vector will be deallocated

}

main()
{
   float* arr;
   std::size_t size{0};

   someFunc(arr, size);

   // do something with the data
   delete [] arr;
}

Run Code Online (Sandbox Code Playgroud)

如何为数组分配数据,std::vector并确保不会调用取消分配std::vector?也许还有其他想法可以解决这个问题?

c++ stdvector move-semantics

4
推荐指数
1
解决办法
102
查看次数

标签 统计

c++ ×1

move-semantics ×1

stdvector ×1