如何将一个队列的值(不是它的引用)排队到另一个队列? 它的工作方式就像我在C ++中有一个点队列(Queue <* word>)一样,但是我想像这样复制缓冲区队列的值
a = 1;
int[] array = new int[1]
array[0] = a //array[0] now is 1
a = 0 // but array[0] doesn't change, array[0] is 1!
我的单词有问题。入队(缓冲区)
using word = System.Collections.Generic.Queue<char>;
Queue<word> words = new Queue<word>(); //word is the custom type, that was def in file top
word buffer = new word();
for (var symbol_count = 0; symbol_count < text.Length; ++symbol_count)
{
if (text[symbol_count] != ' ' && text[symbol_count] != '.' && text[symbol_count] != ',')
{
buffer.Enqueue(text[symbol_count]); //store one char in word
}
else
{
buffer.Enqueue(text[symbol_count]); //store end of word symbol
words.Enqueue(buffer); //store one word in words queue, but compiler do it like I try to copy a reference of buffer, not it value!!!
//System.Console.WriteLine(words.Count); DEBUG
buffer.Clear(); //clear buffer and when i do this, value in words queue is deleted too!!!
}
}
答案 0 :(得分:3)
问题在于,您在循环中重复使用了相同的buffer
,因此当您清除它时,对它的所有引用也会被清除。
相反,请将本地buffer
设置为对象的 new 实例,以便对其进行任何更改都不会影响我们刚刚存储的引用:
foreach (char chr in text)
{
buffer.Enqueue(chr);
if (chr == ' ' || chr == '.' || chr == ',')
{
words.Enqueue(buffer);
// reassign our local variable so we don't affect the others
buffer = new Queue<char>();
}
}
答案 1 :(得分:1)
将新单词保存到队列中时(顺便说一句,您可能在这里遇到了最后一个单词的错误)
words.Enqueue(buffer);
您不应该使用buffer
变量本身:它包含对临时数据的引用,您需要首先对其进行复制,在下一行中将不会对其进行修改。
尝试例如
words.Enqueue(new word(buffer));