Stack<T> Konstruktorer

Definition

Initierar en ny instans av Stack<T> klassen.

Överlagringar

Name Description
Stack<T>()

Initierar en ny instans av Stack<T> klassen som är tom och har standardinitieringskapaciteten.

Stack<T>(IEnumerable<T>)

Initierar en ny instans av Stack<T> klassen som innehåller element som kopierats från den angivna samlingen och har tillräcklig kapacitet för att hantera antalet kopierade element.

Stack<T>(Int32)

Initierar en ny instans av Stack<T> klassen som är tom och har den angivna initiala kapaciteten eller den ursprungliga standardkapaciteten, beroende på vilket som är störst.

Stack<T>()

Initierar en ny instans av Stack<T> klassen som är tom och har standardinitieringskapaciteten.

public:
 Stack();
public Stack();
Public Sub New ()

Exempel

I följande kodexempel visas den här konstruktorn och flera metoder för den Stack<T> generiska klassen.

Kodexemplet skapar en stack med strängar med standardkapacitet och använder Push metoden för att skicka fem strängar till stacken. Elementen i stacken räknas upp, vilket inte ändrar stackens tillstånd. Metoden Pop används för att ta bort den första strängen från stacken. Metoden Peek används för att titta på nästa objekt i stacken och sedan Pop används metoden för att öppna den.

Metoden ToArray används för att skapa en matris och kopiera stackelementen till den. Sedan skickas matrisen till konstruktorn Stack<T> som tar IEnumerable<T>och skapar en kopia av stacken med ordningen på elementen omvända. Elementen i kopian visas.

En matris som är dubbelt så stor som stacken skapas och CopyTo metoden används för att kopiera matriselementen från mitten av matrisen. Konstruktorn Stack<T> används igen för att skapa en kopia av stacken med ordningen omvända element. Därför är de tre null-elementen i slutet.

Metoden Contains används för att visa att strängen "fyra" finns i den första kopian av stacken, varefter Clear metoden rensar kopian och Count egenskapen visar att stacken är tom.

using System;
using System.Collections.Generic;

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

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

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

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

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

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

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

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

        Console.WriteLine("\nstack2.Contains(\"four\") = {0}",
            stack2.Contains("four"));

        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}

/* This code example produces the following output:

five
four
three
two
one

Popping 'five'
Peek at next item to destack: four
Popping 'four'

Contents of the first copy:
one
two
three

Contents of the second copy, with duplicates and nulls:
one
two
three




stack2.Contains("four") = False

stack2.Clear()

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

let numbers = Stack()
numbers.Push "one"
numbers.Push "two"
numbers.Push "three"
numbers.Push "four"
numbers.Push "five"

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

printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"

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

printfn "\nContents of the first copy:"

for number in stack2 do
    printfn $"{number}"

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

// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2

printfn "\nContents of the second copy, with duplicates and nulls:"

for number in stack3 do
    printfn $"{number}"

printfn
    $"""
stack2.Contains "four" = {stack2.Contains "four"}"""

printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {stack2.Count}"

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

Module Example

    Sub Main

        Dim numbers As New Stack(Of String)
        numbers.Push("one")
        numbers.Push("two")
        numbers.Push("three")
        numbers.Push("four")
        numbers.Push("five")

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

        Console.WriteLine(vbLf & "Popping '{0}'", numbers.Pop())
        Console.WriteLine("Peek at next item to pop: {0}", _
            numbers.Peek())    
        Console.WriteLine("Popping '{0}'", numbers.Pop())

        ' Create another stack, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T). Note that
        ' the order of items on the new stack is reversed.
        Dim stack2 As New Stack(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In stack2
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the stack, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the stack, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second stack, using the constructor that accepts an
        ' IEnumerable(Of T). The elements are reversed, with the null
        ' elements appearing at the end of the stack when enumerated.
        Dim stack3 As New Stack(Of String)(array2)

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

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

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

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

Kommentarer

Kapaciteten för en Stack<T> är antalet element som Stack<T> kan hållas. När element läggs till i en Stack<T>ökas kapaciteten automatiskt efter behov genom att den interna matrisen omplaceras.

Om storleken på samlingen kan uppskattas eliminerar du behovet av att utföra ett antal storleksändringsåtgärder när du lägger till element i Stack<T>.

Kapaciteten kan minskas genom att anropa TrimExcess.

Den här konstruktorn är en O(1)-åtgärd.

Gäller för

Stack<T>(IEnumerable<T>)

Initierar en ny instans av Stack<T> klassen som innehåller element som kopierats från den angivna samlingen och har tillräcklig kapacitet för att hantera antalet kopierade element.

public:
 Stack(System::Collections::Generic::IEnumerable<T> ^ collection);
public Stack(System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.Stack<'T> : seq<'T> -> System.Collections.Generic.Stack<'T>
Public Sub New (collection As IEnumerable(Of T))

Parametrar

collection
IEnumerable<T>

Samlingen som elementen ska kopieras från.

Undantag

collection är null.

Exempel

I följande kodexempel visas den här konstruktorn och flera metoder för den Stack<T> generiska klassen.

Kodexemplet skapar en stack med strängar med standardkapacitet och använder Push metoden för att skicka fem strängar till stacken. Elementen i stacken räknas upp, vilket inte ändrar stackens tillstånd. Metoden Pop används för att ta bort den första strängen från stacken. Metoden Peek används för att titta på nästa objekt i stacken och sedan Pop används metoden för att öppna den.

Metoden ToArray används för att skapa en matris och kopiera stackelementen till den. Sedan skickas matrisen till konstruktorn Stack<T> som tar IEnumerable<T>och skapar en kopia av stacken med ordningen på elementen omvända. Elementen i kopian visas.

En matris som är dubbelt så stor som stacken skapas och CopyTo metoden används för att kopiera matriselementen från mitten av matrisen. Konstruktorn Stack<T> används igen för att skapa en kopia av stacken med ordningen omvända element. Därför är de tre null-elementen i slutet.

Metoden Contains används för att visa att strängen "fyra" finns i den första kopian av stacken, varefter Clear metoden rensar kopian och Count egenskapen visar att stacken är tom.

using System;
using System.Collections.Generic;

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

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

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

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

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

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

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

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

        Console.WriteLine("\nstack2.Contains(\"four\") = {0}",
            stack2.Contains("four"));

        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}

/* This code example produces the following output:

five
four
three
two
one

Popping 'five'
Peek at next item to destack: four
Popping 'four'

Contents of the first copy:
one
two
three

Contents of the second copy, with duplicates and nulls:
one
two
three




stack2.Contains("four") = False

stack2.Clear()

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

let numbers = Stack()
numbers.Push "one"
numbers.Push "two"
numbers.Push "three"
numbers.Push "four"
numbers.Push "five"

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

printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"

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

printfn "\nContents of the first copy:"

for number in stack2 do
    printfn $"{number}"

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

// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2

printfn "\nContents of the second copy, with duplicates and nulls:"

for number in stack3 do
    printfn $"{number}"

printfn
    $"""
stack2.Contains "four" = {stack2.Contains "four"}"""

printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {stack2.Count}"

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

Module Example

    Sub Main

        Dim numbers As New Stack(Of String)
        numbers.Push("one")
        numbers.Push("two")
        numbers.Push("three")
        numbers.Push("four")
        numbers.Push("five")

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

        Console.WriteLine(vbLf & "Popping '{0}'", numbers.Pop())
        Console.WriteLine("Peek at next item to pop: {0}", _
            numbers.Peek())    
        Console.WriteLine("Popping '{0}'", numbers.Pop())

        ' Create another stack, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T). Note that
        ' the order of items on the new stack is reversed.
        Dim stack2 As New Stack(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In stack2
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the stack, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the stack, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second stack, using the constructor that accepts an
        ' IEnumerable(Of T). The elements are reversed, with the null
        ' elements appearing at the end of the stack when enumerated.
        Dim stack3 As New Stack(Of String)(array2)

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

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

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

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

Kommentarer

Kapaciteten för en Stack<T> är antalet element som Stack<T> kan hållas. När element läggs till i en Stack<T>ökas kapaciteten automatiskt efter behov genom att den interna matrisen omplaceras.

Om storleken på samlingen kan uppskattas eliminerar du behovet av att utföra ett antal storleksändringsåtgärder när du lägger till element i Stack<T>.

Kapaciteten kan minskas genom att anropa TrimExcess.

Elementen kopieras till Stack<T> i samma ordning som de läse av IEnumerator<T> samlingen.

Den här konstruktorn är en O(n)-åtgärd, där n är antalet element i collection.

Se även

Gäller för

Stack<T>(Int32)

Initierar en ny instans av Stack<T> klassen som är tom och har den angivna initiala kapaciteten eller den ursprungliga standardkapaciteten, beroende på vilket som är störst.

public:
 Stack(int capacity);
public Stack(int capacity);
new System.Collections.Generic.Stack<'T> : int -> System.Collections.Generic.Stack<'T>
Public Sub New (capacity As Integer)

Parametrar

capacity
Int32

Det inledande antalet element som Stack<T> kan innehålla.

Undantag

capacity är mindre än noll.

Kommentarer

Kapaciteten för en Stack<T> är antalet element som Stack<T> kan hållas. När element läggs till i en Stack<T>ökas kapaciteten automatiskt efter behov genom att den interna matrisen omplaceras.

Om storleken på samlingen kan uppskattas eliminerar du behovet av att utföra ett antal storleksändringsåtgärder när du lägger till element i Stack<T>.

Kapaciteten kan minskas genom att anropa TrimExcess.

Den här konstruktorn är en O(n)-åtgärd, där n är capacity.

Gäller för