Queue<T>.GetEnumerator 메서드

정의

Queue<T>를 반복하는 열거자를 반환합니다.

public:
 System::Collections::Generic::Queue<T>::Enumerator GetEnumerator();
public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator ();
member this.GetEnumerator : unit -> System.Collections.Generic.Queue<'T>.Enumerator
Public Function GetEnumerator () As Queue(Of T).Enumerator

반환

Queue<T>.Enumerator에 대한 Queue<T>입니다.

예제

다음 코드 예제에서는 제네릭 클래스를 Queue<T> 열거할 수 있음을 보여 줍니다. foreach 문(For EachVisual Basic의 for each 경우 C++)은 큐를 열거하는 데 사용됩니다.

이 코드 예제에서는 기본 용량이 있는 문자열 큐를 만들고 메서드를 Enqueue 사용하여 5개의 문자열을 큐에 넣습니다. 큐의 요소는 열거되며 큐의 상태는 변경되지 않습니다. 메서드는 Dequeue 첫 번째 문자열의 큐를 해제하는 데 사용됩니다. 메서드는 Peek 큐에서 다음 항목을 보는 데 사용되며 Dequeue 메서드는 큐를 해제하는 데 사용됩니다.

메서드는 ToArray 배열을 만들고 큐 요소를 복사하는 데 사용되며, 배열은 를 사용하는 생성자에 전달되어 Queue<T> 큐의 복사본을 만듭니다 IEnumerable<T>. 복사본의 요소가 표시됩니다.

큐 크기의 두 배인 배열이 만들어지고 CopyTo 메서드를 사용하여 배열 가운데부터 시작하는 배열 요소를 복사합니다. Queue<T> 생성자는 처음에 세 개의 null 요소가 포함된 큐의 두 번째 복사본을 만드는 데 다시 사용됩니다.

메서드는 Contains 문자열 "4"가 큐의 첫 번째 복사본에 있음을 표시하는 데 사용되며 Clear , 그 후에 메서드는 복사본을 지우고 Count 속성은 큐가 비어 있음을 표시합니다.

using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Queue<string> numbers = new Queue<string>();
        numbers.Enqueue("one");
        numbers.Enqueue("two");
        numbers.Enqueue("three");
        numbers.Enqueue("four");
        numbers.Enqueue("five");

        // A queue can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}",
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());

        // Create a copy of the queue, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Queue<string> queueCopy = new Queue<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in queueCopy )
        {
            Console.WriteLine(number);
        }

        // Create an array twice the size of the queue and copy the
        // elements of the queue, starting at the middle of the
        // array.
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);

        // Create a second queue, using the constructor that accepts an
        // IEnumerable(Of T).
        Queue<string> queueCopy2 = new Queue<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in queueCopy2 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nqueueCopy.Contains(\"four\") = {0}",
            queueCopy.Contains("four"));

        Console.WriteLine("\nqueueCopy.Clear()");
        queueCopy.Clear();
        Console.WriteLine("\nqueueCopy.Count = {0}", queueCopy.Count);
    }
}

/* This code example produces the following output:

one
two
three
four
five

Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'

Contents of the first copy:
three
four
five

Contents of the second copy, with duplicates and nulls:



three
four
five

queueCopy.Contains("four") = True

queueCopy.Clear()

queueCopy.Count = 0
 */
open System
open System.Collections.Generic

let numbers = Queue()
numbers.Enqueue "one"
numbers.Enqueue "two"
numbers.Enqueue "three"
numbers.Enqueue "four"
numbers.Enqueue "five"

// A queue can be enumerated without disturbing its contents.
for number in numbers do
    printfn $"{number}"

printfn $"\nDequeuing '{numbers.Dequeue()}'"
printfn $"Peek at next item to dequeue: {numbers.Peek()}"
printfn $"Dequeuing '{numbers.Dequeue()}'"

// Create a copy of the queue, using the ToArray method and the
// constructor that accepts an IEnumerable<T>.
let queueCopy = numbers.ToArray() |> Queue

printfn $"\nContents of the first copy:"
for number in queueCopy do
    printfn $"{number}"

// Create an array twice the size of the queue and copy the
// elements of the queue, starting at the middle of the
// array.
let array2 = numbers.Count * 2 |> Array.zeroCreate
numbers.CopyTo(array2, numbers.Count)

// Create a second queue, using the constructor that accepts an
// IEnumerable(Of T).
let queueCopy2 = Queue array2

printfn $"\nContents of the second copy, with duplicates and nulls:"
for number in queueCopy2 do
    printfn $"{number}"
printfn $"""\nqueueCopy.Contains "four" = {queueCopy.Contains "four"}"""

printfn $"\nqueueCopy.Clear()"
queueCopy.Clear()
printfn $"queueCopy.Count = {queueCopy.Count}"

// This code example produces the following output:
//       one
//       two
//       three
//       four
//       five
//       
//       Dequeuing 'one'
//       Peek at next item to dequeue: two
//       Dequeuing 'two'
//       
//       Contents of the first copy:
//       three
//       four
//       five
//       
//       Contents of the second copy, with duplicates and nulls:
//       
//       
//       
//       three
//       four
//       five
//       
//       queueCopy.Contains "four" = True
//       
//       queueCopy.Clear()
//       
//       queueCopy.Count = 0
Imports System.Collections.Generic

Module Example

    Sub Main

        Dim numbers As New Queue(Of String)
        numbers.Enqueue("one")
        numbers.Enqueue("two")
        numbers.Enqueue("three")
        numbers.Enqueue("four")
        numbers.Enqueue("five")

        ' A queue can be enumerated without disturbing its contents.
        For Each number As String In numbers
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "Dequeuing '{0}'", numbers.Dequeue())
        Console.WriteLine("Peek at next item to dequeue: {0}", _
            numbers.Peek())    
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue())

        ' Create a copy of the queue, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T).
        Dim queueCopy As New Queue(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In queueCopy
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the queue, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the queue, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second queue, using the constructor that accepts an
        ' IEnumerable(Of T).
        Dim queueCopy2 As New Queue(Of String)(array2)

        Console.WriteLine(vbLf & _
            "Contents of the second copy, with duplicates and nulls:")
        For Each number As String In queueCopy2
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "queueCopy.Contains(""four"") = {0}", _
            queueCopy.Contains("four"))

        Console.WriteLine(vbLf & "queueCopy.Clear()")
        queueCopy.Clear()
        Console.WriteLine(vbLf & "queueCopy.Count = {0}", _
            queueCopy.Count)
    End Sub
End Module

' This code example produces the following output:
'
'one
'two
'three
'four
'five
'
'Dequeuing 'one'
'Peek at next item to dequeue: two
'
'Dequeuing 'two'
'
'Contents of the copy:
'three
'four
'five
'
'Contents of the second copy, with duplicates and nulls:
'
'
'
'three
'four
'five
'
'queueCopy.Contains("four") = True
'
'queueCopy.Clear()
'
'queueCopy.Count = 0

설명

합니다 foreach C# 언어의 (for each c + +에서는 For Each Visual Basic에서) 열거자의 복잡성을 숨깁니다. 그러므로 열거자를 직접 조작하는 대신 foreach를 사용하는 것이 좋습니다.

열거자를 사용하여 컬렉션의 데이터를 읽을 수는 있지만 내부 컬렉션을 수정할 수는 없습니다.

처음에 열거자는 컬렉션의 첫 번째 요소 앞에 배치됩니다. 이 위치에서 Current는 정의되지 않습니다. 따라서 MoveNext의 값을 읽기 전에 Current를 호출하여 열거자를 해당 컬렉션의 첫 번째 요소로 보내야 합니다.

CurrentMoveNext가 호출될 때까지 동일한 개체를 반환합니다. MoveNextCurrent를 다음 요소로 설정합니다.

경우 MoveNext 열거자를 컬렉션의 끝 컬렉션의 마지막 요소 뒤에 배치 되는 전달 하 고 MoveNext 반환 false합니다. 열거자가 있는 경우이 위치에 대 한 후속 호출은 MoveNext 반환할 수도 false합니다. 반환 falseCurrent 된 에 대한 MoveNext 마지막 호출이 정의되지 않은 경우 Current를 컬렉션의 첫 번째 요소로 다시 설정할 수 없으므로 대신 새 열거자 인스턴스를 만들어야 합니다.

컬렉션이 변경되지 않고 그대로 유지되는 한 열거자는 유효한 상태로 유지됩니다. 변경에 추가 하는 등 컬렉션을 수정 하거나 요소를 삭제, 열거자가 복구할 유효 하지 않으며을 다음에 호출할 MoveNext 또는 IEnumerator.Reset throw는 InvalidOperationException합니다.

열거자는 컬렉션에 배타적으로 액세스하지 못하므로 컬렉션을 열거하는 것은 본질적으로 스레드로부터 안전한 프로시저가 아닙니다. 열거 동안 스레드 보안을 보장하려면 전체 열거 동안 컬렉션을 잠그면 됩니다. 여러 스레드에서 컬렉션에 액세스하여 읽고 쓸 수 있도록 허용하려면 사용자 지정 동기화를 구현해야 합니다.

에서 System.Collections.Generic 컬렉션의 기본 구현은 동기화되지 않습니다.

이 방법은 O(1) 작업에 설명 합니다.

적용 대상

추가 정보