Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a queue interact with a foreach loop

Tags:

I was really suprised that this question doesn't really have an answer. For example I have a foreach loop iterating through the queue(I am using the .Net versions) what exactly happens to the queue in the foreach? Does it simply iterates like a standard enumerator? Or does it use the Dequeue() functionality.

For clarity:

Queue<int> q = new Queue<int>();
foreach(int i in q)
{
    // what happens in this loop?
}
like image 289
Headhunter Xamd Avatar asked Sep 24 '15 08:09

Headhunter Xamd


People also ask

How does a foreach loop work?

How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.

What can foreach statements iterate through?

The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.


1 Answers

Does it simply iterates like a standard enumerator? Or does it use the Dequeue()

Instead of iterating the queue, it looks up elements by index and bucket in its internal array, using the Queue<T>.GetElement method. You can see this in the implementation of the Enumerator class returned by Queue<T>.GetEnumerator():

public bool MoveNext() 
{
    if (_version != _q._version)
        ThrowHelper.ThrowInvalidOperationException(
                                    ExceptionResource.InvalidOperation_EnumFailedVersion);

    if (_index == -2)
        return false;

    _index++;

    if (_index == _q._size) 
    {
        _index = -2;
        _currentElement = default(T);
        return false;
    }

    _currentElement = _q.GetElement(_index);
    return true;
}

Where GetElement is simply:

internal T GetElement(int i)
{
    return _array[(_head + i) % _array.Length];
}
like image 61
Yuval Itzchakov Avatar answered Oct 11 '22 17:10

Yuval Itzchakov