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

问题描述 投票:0回答:1

如何在不复制或迭代所有元素的情况下将std :: vector的内容轻松地移动到数组中

void (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;
}

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

c++ stdvector move-semantics
1个回答
2
投票
向量拥有其缓冲区。

您不能偷它。

您将必须以块(std::copy / std::move)或单独复制/移动元素。

请考虑是否

确实需要执行此操作。只要使向量保持活动状态,就可以在需要时使用vec.data()将向量的数据视为数组。当然,这比牺牲RAII更好吗?

© www.soinside.com 2019 - 2024. All rights reserved.