简体   繁体   中英

How to set value of queue to another queue?

How can I enqueue value of a queue (not it reference) to another queue? It work like I have a queue of points in C++ (Queue<*word>), but I want to copy value of buffer queue like this

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!

I have problem in 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!!!
    }
}

The problem is that you're re-using the same buffer in your loop, so when you clear it, all the references to it are also cleared.

Instead, set the local buffer variable to a new instance of the object, so that any changes to it don't affect the reference we just stored:

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

When you save a new word to a queue (you might have a bug with the last word here, by the way)

words.Enqueue(buffer);

You shouldn't use the buffer variable itself: it holds a reference to the temporary data and you need to make a copy of it first, something that will not be modified in the next lines.

Try eg

words.Enqueue(new word(buffer));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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