如何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?也许还有其他想法可以解决这个问题?