本人,队列要怎么学

.Net技术 码拜 8年前 (2016-05-31) 820次浏览
用for循环进队列,为什么出队列都是一样的值,是不是进队列的值没有修改,只有最后一次的循环值进了队列?
static void Main(string[] args)
{
Queue<int[]> a = new Queue<int[]>();
int[] x={1,1,2};
int[] y = { 0, 0, 0 };
for (int i = 0; i < 10; i++)
{
a.Enqueue(x);
x[0] = i;
x[1] = i;
x[2] = i;
Console.WriteLine(“{0},{1},{2},”, x[0], x[1], x[2]);
}
while(a.Count>0)
{
y = a.Dequeue();
Console.WriteLine(“{0},{1},{2},”,y[0],y[1],y[2]);

}
Console.ReadKey();
}
本人,队列要怎么学

解决方案

5

Queue<int[]> a = new Queue<int[]>();
int[] x={1,1,2};
for (int i = 0; i < 10; i++)
{
    a.Enqueue(x);
    x=new int[] {i, i, i};
    Console.WriteLine("{0},{1},{2},", x[0], x[1], x[2]);
}

30

首先要知道,你的队列a中的元素是一个数组
for (int i = 0; i < 10; i++){}
执行1次后,a{{0,0,0}}
执行2次后,a{{1,1,1},{1,1,1}}
执行3次后,a{{2,2,2},{2,2,2},{2,2,2}}
……
执行10此后,全部是9,a{{9,9,9},……,{9,9,9}},而不是你想象的a{{1,1,1},……,{9,9,9}}
原因很简单,数组是引用类型,a里严格讲是存储了数组x相同的引用(数值的地址),a中一个元素的值改变,全变了
按照你的思路,应该这样改:

Queue<int[]> a = new Queue<int[]>();
int[] x = { 1, 1, 2 };
int[] y = { 0, 0, 0 };
for (int i = 0; i < 10; i++)
{
    //a.Enqueue(new int[] { i, i, i });
    a.Enqueue(x);               
    x = new int[3]; //每次循环new下,表示把数值保存到不同地址,这样a中各个元素就互不干扰了
    x[0] = i;
    x[1] = i;
    x[2] = i;
    Response.Write(string.Format("{0},{1},{2},", x[0], x[1], x[2])+"<br />");
}
while (a.Count > 0)
{
    y = a.Dequeue();
    Response.Write(string.Format("{0},{1},{2},", y[0], y[1], y[2]) + "<br />") ;
} 

或干脆不用x数组,直接用//a.Enqueue(new int[] { i, i, i })

5

都是一样的值 与队列没有任何关系
数组传递的是引用,并不会原因是是队列而改变
在你没有理解这个基础问题时,你怎么写都是要出问题的

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明本人,队列要怎么学
喜欢 (0)
[1034331897@qq.com]
分享 (0)