繁体   English   中英

如何将队列的值设置为另一个队列?

[英]How to set value of queue to another queue?

如何将一个队列的值(不是它的引用)排队到另一个队列? 它像我在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!!!
    }
}

问题是您在循环中重新使用了相同的buffer ,因此当您清除它时,对它的所有引用也会被清除。

而是将局部buffer变量设置为对象的实例,以便对其进行任何更改都不会影响我们刚刚存储的引用:

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>();   
    }
}

当您将新单词保存到队列中时(顺便说一句,您可能在这里遗漏了一个单词)

words.Enqueue(buffer);

您不应该使用buffer变量本身:它持有对临时数据的引用,您需要首先对其进行复制,在下一行中不会对其进行修改。

尝试例如

words.Enqueue(new word(buffer));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM