以下代碼演示了我在大型應用程式中遇到的問題。
void probtest() {
List<List<int>> mat1 = List.filled(3, List.filled(3, -1));
List<List<int>> mat2 = [
[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1]
];
print(mat1);
print(mat2);
mat1[0][0] = 1;
mat2[0][0] = 1;
print(mat1);
print(mat2);
}
這個的輸出(為清楚起見而格式化)是:
[
[-1,-1,-1],
[-1,-1,-1],
[-1,-1,-1]
]
[
[-1,-1,-1],
[-1,-1,-1],
[-1,-1,-1]
]
[
[1,-1,-1],
[1,-1,-1],
[1,-1,-1]
]
[
[1,-1,-1],
[-1,-1,-1],
[-1,-1,-1]
]
如您所見,使用 List.filled 創建矩陣,然后嘗試更新 [0][0] 處的值似乎會更新整個第 0 列。如果矩陣是使用文字創建的,那么更新 [0][0] 只會更新 [0][0] 項 - 這是我想要和預期的結果。
2個問題:
- 為什么不一樣?
- 有沒有一種方法可以在不手動寫出文字的情況下初始化串列,以便我能夠像 mat2 一樣更新單個專案。我需要為更大的矩陣做這件事。
uj5u.com熱心網友回復:
編碼
List<List<int>> mat1 = List.filled(3, List.filled(3, -1));
創建一個List.filled(3, -1),然后創建另一個與所有三個元素具有相同串列的串列。
當您更新一個串列時,它會在參考該串列的任何地方顯示。
你應該做的是:
List<List<int>> mat1 = List.generate(3, (_) => List.filled(3, -1));
這將為外部串列的每個元素創建一個新串列,而不是重用相同的串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515908.html
標籤:列表镖矩阵
