在C++中,代碼如下所示:
#include <vector>
void function()
{
std::vector<double> array(100);
//some work that can return when or throw an exception
//...
return;
}
如果你真的不想初始化數組元素且並不需要調整的數組,不需要迭代,你也可以使用:
#include <memory>
void function()
{
std::unique_ptr<double[]> array(new double[100]);
//some work that can return when or throw an exception
//...
return;
}
在這兩種情況下,你訪問數組元素與array[0]
,array[1]
等
最後,如果你不需要ŧ O傳輸數據的所有權出來的功能,在編譯時知道數組的大小,規模不是太大,你也可以考慮具有直接數組對象:
void function()
{
double array[100]; // uninitialized, add " = {}" to zero-initialize
// or:
std::array<double, 100> array; // ditto
//some work that can return when or throw an exception
//...
return;
}
是的。在「智能指針」上運行Google搜索。 –
或更好的['std :: array'](http://en.cppreference.com/w/cpp/container/array)(或可能['std :: vector'](http://en.cppreference)的.com /瓦特/ CPP /容器/載體))。 –
閱讀RAII成語,用於Rust和C++。 –