我要初始化指针数组。(不是一个普通的数组)但是这不起作用。
int* arr = new int [5];
arr = {1,2,3,4,5};
我也不想这样做(因为如果大小改变,我必须改变代码)
arr[0] = 1; arr[1] = 2; ...
是否有简单的方法来做到这一点?那么矩阵呢?
int** mat = ...
mat = { {1,2} , {3,4} }
我也不想这样初始化:(因为当我想把矩阵传递给函数时,有一些限制(例如:如果大小改变,我必须改变函数定义))
int mat[2][2] = { {1,2} , {3,4} };
你可以这样写:
int* arr = new int [5] { 1, 2, 3, 4, 5 };
或者你可以使用算法std::iota
,比如
int* arr = new int [5];
std::iota( arr, arr + 5, 1 );
或其他算法,例如std::fill
或std::generate
。
如果数组将被重新分配,那么在这种情况下使用标准容器std::vector<int>
要好得多。
(例如:如果大小改变,我必须改变函数定义))
可以将函数定义为模板函数,其中数组的大小将是模板非类型参数。
如果你真的想要自己动态创建一个数组,然后按照@Vlad from Moscow的建议:
int* arr = new int [5] {1, 2, 3, 4, 5};
或:
int* arr = new int [5];
std::iota( arr, arr + 5, 1 ); // also std::fill or std::generate
但是,99%的情况下,使用std::vector
几乎在各个方面都更好。
你的代码看起来像这样:
std::vector<int> arr{1, 2, 3, 4, 5};
// if you know the size of the array at runtime, then do this
arr.resize(5 /* size of the array at runtime */)
更好的是,如果你在编译时知道数组的大小,那么std::array
是你最好的朋友。
std::array<int, 5 /* size of the array at compile time */> arr{1, 2, 3, 4, 5};
下面是一个使用std::make_unique来避免new/delete的例子。但是,正如您所看到的,数组大小必须手动维护。所以你还是使用std::vector或者std::array
比较好#include <algorithm>
#include <iostream>
#include <memory>
// allocate with make_unqiue and initialize from list
template<typename type_t, std::size_t N>
auto make_array(const type_t (&values)[N])
{
std::unique_ptr<type_t[]> array_ptr = std::make_unique<type_t[]>(N);
for (std::size_t n = 0; n < N; ++n) array_ptr[n] = values[n];
return array_ptr;
}
int main()
{
auto array_ptr = make_array({ 1,2,3,4,5 });
for (std::size_t n = 0; n < 5; ++n)
{
std::cout << array_ptr[n] << " ";
}
// std::unique_ptr will take care of deleting the memory
}