作者rahim (forget it)
看板C_Sharp
標題Re: [問題] 如何用C#寫一個動態陣列?
時間Fri Mar 23 22:42:08 2007
※ 引述《rahim (forget it)》之銘言:
: ※ 引述《GreatShot (我要拿Ph.D.!!!)》之銘言:
: : 抱歉這裡我筆誤 應該是arr.Count
: : 是的 每個ArrayList的元素是"各自"指向一個全新的ArrayList
: : 沒那麼美好..XD
: : ArrayList有時很方便有時也很麻煩
: : 因為ArrayList裡頭不管你放什麼東西都會被轉成object
: : 所以你要取用時得先cast一下
: : 會變成 ((ArrayList)arr[i])[j]
: : 所以我建議你去研究一下System.Collections.Generic裡頭的類別
: : 這是.NET 2.0才有的東西
: : 效率比ArrayList高很多
: System.Collections.Generic裡面的類別
: 跟ArrayList比較接近的 是List泛型類別嗎?
: http://msdn2.microsoft.com/zh-tw/library/6sh2ey19(VS.80).aspx
如果想要依照使用者輸入的要求
建立一個m X n的動態陣列
那下面這樣寫可以嗎?
Console.WriteLine("Please input the row size of matrix");
int m =Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please input the column size of matrix");
int n = Convert.ToInt32(Console.ReadLine());
List<List<double>> arr = new List<List<double>>();
for (int i = 0; i < m; i++)
{
arr[i] = new List<double>();
for (int j = 0; j < n; j++)
{
arr[i][j] = i + j;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.119.144.40
推 tomex:看起來ok 03/24 00:59
推 tomex:不過list<>要用add()把值塞進去,未配大小時就充值不行 03/24 01:01
推 rahim:所以是改成arr.Add(new List<double>()); 03/24 04:02
→ rahim:下面改成arr[i].Add(i+j); 這樣以後就可以用arr[i][j]了嗎? 03/24 04:03
→ rahim:還有想請問一下List< >中間要放的是什麼? 03/24 04:04
→ rahim:為什麼我一開始用 03/24 04:05
→ rahim:List<List<double>> arr=new List<List<double>>(); 03/24 04:06
→ rahim:這樣可以呢?(雖然是我自己想出來的,不過想聽一下講解) 03/24 04:07