Stack代表一個last-in,對象的先出集合。當您需要對項目進行 last-in、first-out 訪問時使用它。當你在列表中添加一個項目時,它被稱為推送項目,當你刪除它時,它被稱為彈出項目。 Stack<T>.ToArray 方法用於將 Stack<T> 複製到新數組。
屬性:
- Stack 的容量是 Stack 可以容納的元素數量。隨著元素被添加到堆棧中,容量會根據需要通過重新分配自動增加。
- 如果 Count 小於堆棧的容量,則 Push 是 O(1) 操作。如果需要增加容量以容納新元素,則 Push 變為 O(n) 操作,其中 n 為 Count。 Pop 是一個 O(1) 操作。
- Stack 接受 null 作為有效值並允許重複元素。
用法:
public T[] ToArray ();
返回類型:此方法返回一個新數組 t[],其中包含 Stack<T> 元素的副本。
下麵給出了一些示例,以更好地理解實現:
範例1:
// C# code to Convert Stack to array
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack of strings
Stack<string> myStack = new Stack<string>();
// Inserting the elements into the Stack
myStack.Push("Geeks");
myStack.Push("Geeks Classes");
myStack.Push("Noida");
myStack.Push("Data Structures");
myStack.Push("GeeksforGeeks");
// Converting the Stack into array
String[] arr = myStack.ToArray();
// Displaying the elements in array
foreach(string str in arr)
{
Console.WriteLine(str);
}
}
}
輸出:
GeeksforGeeks Data Structures Noida Geeks Classes Geeks
範例2:
// C# code to Convert Stack to array
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack of Integers
Stack<int> myStack = new Stack<int>();
// Inserting the elements into the Stack
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);
myStack.Push(6);
// Converting the Stack into array
int[] arr = myStack.ToArray();
// Displaying the elements in array
foreach(int i in arr)
{
Console.WriteLine(i);
}
}
}
輸出:
6 5 4 3 2
參考:
相關用法
- C# Stack.Peek用法及代碼示例
- C# Stack用法及代碼示例
- C# Stack.Count用法及代碼示例
- C# Stack.IsSynchronized用法及代碼示例
- C# Stack.Contains()用法及代碼示例
- C# Stack.Clear用法及代碼示例
- C# Stack.CopyTo()用法及代碼示例
- C# Stack.GetEnumerator用法及代碼示例
- C# Stack.Push()用法及代碼示例
- C# Stack.Pop()用法及代碼示例
- C# Stack.ToArray()用法及代碼示例
- C# Stack.Synchronized()用法及代碼示例
- C# Stack.Equals()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 C# | Convert Stack to array。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。