【问题标题】:How to set value of queue to another queue?如何将队列的值设置为另一个队列?
【发布时间】:2019-12-10 10:44:27
【问题描述】:

如何将一个队列的值(不是它引用)排入另一个队列? 它的工作方式就像我在 C++ 中有一个点队列(Queue),但我想像这样复制缓冲区队列的值

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!

words.Enqueue(buffer) 有问题

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!!!
    }
}

【问题讨论】:

  • “我的 word.Enqueue(buffer) 有问题”。那么问题出在哪里?
  • 我在“单词”队列中插入的不是“缓冲区”队列的值,而是指针。当我更改“缓冲区”队列的值时,它也会在“单词”队列中更改。但我只想在“单词”队列中复制“缓冲区”队列的值
  • 当你使用别名Queue&lt;char&gt;时读起来有点混乱
  • stackoverflow.com/questions/16209747/cloning-queue-in-c-sharp 的副本。或者只是创建一个新队列而不是 Clearing 旧队列。
  • 我不确定我是否完全理解您的问题,但听起来您想在队列中制作一个值的深层副本并将其排入另一个队列?这是一个可能有帮助的链接:stackoverflow.com/questions/129389/…

标签: c# queue


【解决方案1】:

当您将一个新单词保存到队列中时(顺便说一下,您可能会遇到最后一个单词的错误)

words.Enqueue(buffer);

您不应该使用 buffer 变量本身:它包含对临时数据的引用,您需要先复制它,在接下来的行中不会修改。

试试例如

words.Enqueue(new word(buffer));

【讨论】:

  • 感谢您的帮助!
  • @MagicianArtemka 欢迎您。但请注意,我在这里回答了您的问题,基本上是如何使用队列值并将其从队列引用中“分离”。然而,对于潜在的问题,Rufus 的代码更加直接和高效。
【解决方案2】:

问题是您在循环中重复使用相同的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>();   
    }
}

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
相关资源
最近更新 更多