[英]Resizing and initializing 2D array C#
I have a 2D array of type string
which I want to modify and resize inside some loop. 我有一个
string
类型的2D数组,我想在某个循环内修改和调整大小。 My main goal is to use minimum memory by creating a 2d array which will be modified every iteration of loop and the add a char to an appropriate cell in this array. 我的主要目标是通过创建一个2d数组来使用最少的内存,该数组将在每次循环迭代时进行修改,并在此数组中的适当单元格中添加一个char。 Here is my code:
这是我的代码:
static void Main(string[] args)
{
int maxBound = 100;//length of freq array
Random rnd1 = new Random();
int numLoops = rnd1.Next(1000, 1200);//number of total elements in freq array
int[] freq = new int[maxBound];//freq array
string[,] _2dim = new string[maxBound, numLoops];//rows,columns
Random rnd2 = new Random();
for (int i = 0; i < numLoops; i++)
{
int s = rnd2.Next(maxBound);
freq[s]++;
//Here I try to add `*` to the _2dim array while resizing it to the appropriate size
}
}
What is the main approach for the solution ? 解决方案的主要方法是什么? Thanks
谢谢
Instead of a 2D array you might want to use a jagged one. 您可能要使用锯齿状的阵列,而不是二维阵列。 Briefly, a 2D array is always an N x M matrix, which you cannot resize, whereas a jagged array is an array of arrays, where you can separately initialize every inner element by a different size (see the differences in details here )
简而言之,二维数组始终是N x M矩阵,您无法调整其大小,而锯齿数组是数组的数组,您可以在其中以不同的大小分别初始化每个内部元素(请参见此处的详细信息)
int maxBound = 100;
Random rnd = new Random();
int numLoops = rnd.Next(1000, 1200);
string[][] jagged = new string[numLoops][];
for (int i = 0; i < numLoops; i++)
{
int currLen = rnd.Next(maxBound);
jagged[i] = new string[currLen];
for (int j = 0; j < currLen; j++)
jagged[i][j] = "*"; // do some initialization
}
You should use a list of type string
nested in a List. 您应该使用嵌套在列表中的
string
类型列表。 Then you can modify this lists. 然后,您可以修改此列表。 For iterating through this you should use two for loops.
为了对此进行迭代,您应该使用两个for循环。
List<List<string>> l = new List<List<string>> { new List<string> { "a", "b" }, new List<string> { "1", "2" } };
Iteration example: 迭代示例:
for(int i = 0; i < l.Count; i++)
{
for(int j = 0; j < l[i].Count; j++)
{
Console.WriteLine(l[i][j]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.