gpt4 book ai didi

C#列表列表问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:06 24 4
gpt4 key购买 nike

我还有一个关于列表列表的问题。再一次,我有如下通用矩阵类。

public class Matrix<T>
{
List<List<T>> matrix;

public Matrix()
{
matrix = new List<List<T>>();
}

public void Add(IEnumerable<T> row)
{
List<T> newRow = new List<T>(row);
matrix.Add(newRow);
}
}

// Test code
Matrix<double> matrix = new Matrix<double>();
matrix.Add(new List<double>() { 0, 0 });
matrix.Add(new List<double>() { 16.0, 4.0 });

我正在从包含以下格式值的文本文件中读取字符串行,

4 2

0.5 0.4 0.6 0.1 10.1 11.1 0.5 12.0

第一行指定 4x2 矩阵大小。第二行需要使前 4 个值位于矩阵的第一列中,最后四个值应位于第二列中。这是动态的,因此大小不固定。

读取行并分隔这些行是排序的。我的问题是关于如何使用 Matrix 类来存储这些值。换句话说,我怎样才能连续做这些元素?

应该让矩阵看起来像,

0.5 10.1

0.4 11.1

0.6 0.5

0.1 12.0

提前致谢。

最佳答案

你的矩阵维度真的应该是可变的吗?一个更好的选择可能是在构造函数中传递它的维度并在矩阵中分配数组:

public class Matrix<T>
{
private readonly T[][] _matrix;

public Matrix(int rows, int cols)
{
_matrix = new T[rows][];
for (int r = 0; r < rows; r++)
_matrix[r] = new T[cols];
}

public T this[int r, int c]
{
get { return _matrix[r][c]; }
set { _matrix[r][c] = value; }
}
}

或者,如果它确实需要可变,您可以根据需要选择“惰性”分配它:

public class Matrix<T>
{
private readonly List<List<T>> _matrix;

public Matrix()
{
_matrix = new List<List<T>>();
}

public T this[int r, int c]
{
get
{
ResizeIfNeeded(r, c);
return _matrix[r][c];
}
set
{
ResizeIfNeeded(r, c);
_matrix[r][c] = value;
}
}

private void ResizeIfNeeded(int row, int col)
{
while (_matrix.Count <= r)
_matrix.Add(new List<T>());

var row = _matrix[r];
while (row.Count <= c)
row.Add(default(T));
}
}

请注意,如果您按顺序填充,第二种方法可能会进行大量分配。

我会选择第一种方法(固定大小的矩阵),因为在大多数情况下它的维度是已知的。它的分配速度最快,并且在多线程应用程序中使用它是安全的。

如果您从文件中读取值,通过索引设置它们应该比为每一行实例化一个新列表简单得多。

关于C#列表列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7738096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com