[英]initialize array of pointer and matrix
I want to initialize array of pointer.(not a normal array) But this doesn't work.我想初始化指针数组。(不是普通数组)但这不起作用。
int* arr = new int [5];
arr = {1,2,3,4,5};
Also I don't want to do it like this:(Because if the size changes I have to change the code)我也不想这样做:(因为如果大小改变我必须改变代码)
arr[0] = 1; arr[1] = 2; ...
Is there an easy way to do this?是否有捷径可寻? what about a matrix?矩阵呢?
int** mat = ...
mat = { {1,2} , {3,4} }
And also I don't want initialize like this: (Because when I want to pass the matrix to a function there are some limits (For example: If size changes, I have to change function defenition))而且我也不希望像这样初始化:(因为当我想将矩阵传递给函数时有一些限制(例如:如果大小发生变化,我必须更改函数定义))
int mat[2][2] = { {1,2} , {3,4} };
You can write for example你可以写例如
int* arr = new int [5] { 1, 2, 3, 4, 5 };
Or for example you could use the algorithm std::iota
like或者例如你可以使用算法std::iota
像
int* arr = new int [5];
std::iota( arr, arr + 5, 1 );
or some other algorithm as for example std::fill
or std::generate
.或其他一些算法,例如std::fill
或std::generate
。
If the array will be reallocated then it is much better in this case to use the standard container std::vector<int>
.如果数组将被重新分配,那么在这种情况下最好使用标准容器std::vector<int>
。
(For example: If size changes, I have to change function defenition)) (例如:如果大小改变,我必须改变函数定义))
You can define the function as a template function where the size of an array will be a template non-type parameter.您可以将该函数定义为模板函数,其中数组的大小将是模板非类型参数。
If you really want to dynamically create an array yourself then do what @Vlad from Moscow recommends:如果您真的想自己动态创建一个数组,那么请按照莫斯科的@Vlad 的建议进行操作:
int* arr = new int [5] {1, 2, 3, 4, 5};
or:或者:
int* arr = new int [5];
std::iota( arr, arr + 5, 1 ); // also std::fill or std::generate
But, 99% of the time, using std::vector
is almost better every way.但是,在 99% 的情况下,使用std::vector
几乎在各方面都更好。
Your code would look like this:您的代码如下所示:
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 */)
Even better, if you know the size of the array at compile time then std::array
is your best friend.更好的是,如果您在编译时知道数组的大小,那么std::array
是您最好的朋友。
std::array<int, 5 /* size of the array at compile time */> arr{1, 2, 3, 4, 5};
#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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.