Stackとは? わかりやすく解説

スタック【stack】


スタック

【英】stack

スタックとは、データ構造の一つであるリストの中で、特に挿入、削除がリストの先頭からしかできないものである。このような構造は、LIFO(後入れ先出し)と呼ばれる。

スタックは、例で言えば、机上に積み上げられた本のような構造をしている。本は上に積み上げられていき、読みたい本は上から順に取っていかなければ取れないという点が、スタックと似ている。

スタックは、情報処理のさまざまな場面に欠かせないデータ構造であるといえる。プログラムがサブルーチンを実行後に呼び出し元に戻る仕組みには、スタックが使われる。サブルーチンを実行する前に、スタックに戻り先を積み上げ(PUSH)、サブルーチンが処理を終わると、戻り先、つまり次にプログラムを実行する番地を取り出す(POP)。文書編集操作の「やり直し」や「元にもどす」などもスタックを利用して実現されているのが一般的である。

情報処理のほかの用語一覧
アルゴリズム:  シーケンシャルサーチ  挿入ソート  ソート  スタック  2分木  2分探索木  2分探索法

Stack クラス

オブジェクトの単純な後入れ先出し (LIFO) 非ジェネリック コレクションを表します。

名前空間: System.Collections
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class Stack
    Implements ICollection, IEnumerable, ICloneable
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class Stack : ICollection, IEnumerable,
 ICloneable
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class Stack : ICollection, IEnumerable,
 ICloneable
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class Stack implements ICollection,
 IEnumerable, 
    ICloneable
SerializableAttribute 
ComVisibleAttribute(true) 
public class Stack implements ICollection,
 IEnumerable, 
    ICloneable
解説解説

このコレクションのジェネリック バージョンについては、「System.Collections.Generic.Stack」を参照してください。

Stack は、循環バッファとして実装されます。

Stack の容量は、Stack が保持できる要素数になります。Stack の既定の初期量は 10 です。Stack に要素を追加すると、必要に応じて、再割り当てによって容量が自動的に増加します。

Count がスタックの容量よりも小さい場合、Push は O(1) 操作になります。新しい要素を格納するために容量を増やす必要がある場合、Push は O(n) 操作になります。ここで、n は Count です。Pop は O(1) 操作です。

Stack は、null 参照 (Visual Basic では Nothing) を有効な値として受け取り、要素の重複を許可します。

使用例使用例

Stack を作成して値を追加する方法と、その値を出力する方法の例を次に示します。

Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesStack    
    
    Public Shared Sub Main()
    
        ' Creates and initializes a new Stack.
        Dim myStack As New
 Stack()
        myStack.Push("Hello")
        myStack.Push("World")
        myStack.Push("!")
        
        ' Displays the properties and values of the Stack.
        Console.WriteLine("myStack")
        Console.WriteLine(ControlChars.Tab & "Count:    {0}",
 myStack.Count)
        Console.Write(ControlChars.Tab & "Values:")
        PrintValues(myStack)
    End Sub
    
    Public Shared Sub PrintValues(myCollection
 As IEnumerable)
        Dim obj As [Object]
        For Each obj In
  myCollection
            Console.Write("    {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub 'PrintValues

End Class

' This code produces the following output.
'
' myStack
'     Count:     3
'     Values:    !    World    Hello
using System;
using System.Collections;
public class SamplesStack  {

   public static void Main()
  {

      // Creates and initializes a new Stack.
      Stack myStack = new Stack();
      myStack.Push("Hello");
      myStack.Push("World");
      myStack.Push("!");

      // Displays the properties and values of the Stack.
      Console.WriteLine( "myStack" );
      Console.WriteLine( "\tCount:    {0}", myStack.Count );
      Console.Write( "\tValues:" );
      PrintValues( myStack );
   }

   public static void PrintValues(
 IEnumerable myCollection )  {
      foreach ( Object obj in myCollection
 )
         Console.Write( "    {0}", obj );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

myStack
    Count:    3
    Values:    !    World    Hello
*/ 

using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myCollection );
int main()
{
   
   // Creates and initializes a new Stack.
   Stack^ myStack = gcnew Stack;
   myStack->Push( "Hello" );
   myStack->Push( "World" );
   myStack->Push( "!" );
   
   // Displays the properties and values of the Stack.
   Console::WriteLine( "myStack" );
   Console::WriteLine( "\tCount:    {0}", myStack->Count );
   Console::Write( "\tValues:" );
   PrintValues( myStack );
}

void PrintValues( IEnumerable^ myCollection )
{
   IEnumerator^ myEnum = myCollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "    {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 myStack
     Count:    3
     Values:    !    World    Hello
 */
import System.*;
import System.Collections.*;

public class SamplesStack
{
    public static void main(String[]
 args)
    {
        // Creates and initializes a new Stack.
        Stack myStack = new Stack();

        myStack.Push("Hello");
        myStack.Push("World");
        myStack.Push("!");

        // Displays the properties and values of the Stack.
        Console.WriteLine("myStack");
        Console.WriteLine("\tCount:    {0}", 
            System.Convert.ToString(myStack.get_Count()));
        Console.Write("\tValues:");
        PrintValues(myStack);
    } //main

    public static void PrintValues(IEnumerable
 myCollection)
    {
        IEnumerator objEnum = myCollection.GetEnumerator();

        while (objEnum.MoveNext()) {
            Console.Write("    {0}", objEnum.get_Current());
        }
        Console.WriteLine();
    } //PrintValues

} //SamplesStack

/* 
 This code produces the following output.
 
 myStack
     Count:    3
     Values:    !    World    Hello
 */
継承階層継承階層
System.Object
  System.Collections.Stack
     Microsoft.VisualC.SymbolTableStack
スレッド セーフスレッド セーフ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Stack メンバ
System.Collections 名前空間
System.Collections.Generic.Stack

Stack コンストラクタ ()

空で、既定の初期量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ ()

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

空で、既定の初期量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections.Generic
アセンブリ: System (system.dll 内)
構文構文

解説解説
使用例使用例

このコンストラクタおよび Stack ジェネリック クラスのいくつかのメソッドを使用したコード例を次に示します。

このコード例では、既定の容量で文字列のスタックを作成し、Push メソッドを使用して 5 つの文字列をスタックにプッシュします。スタックの要素は列挙されますが、スタックの状態は変化しません。Pop メソッドを使用して、最初の文字列をスタックからポップします。Peek メソッドを使用してスタック内の次の項目を調べてから、Pop メソッドを使用してその項目をスタックからポップします。

ToArray メソッドを使用して配列を作成し、その配列にスタック要素をコピーしてから、IEnumerable を受け取る Stack コンストラクタに配列を渡して、要素の順序を反転したスタックのコピーを作成します。コピーの要素が表示されます。

スタックの 2 倍のサイズの配列が作成され、CopyTo メソッドを使用して配列の中央部で始まる配列要素をコピーします。Stack コンストラクタを再度使用して、要素の順序を反転したスタックのコピーを作成します。その結果、3 つの null 要素が末尾に配置されます。

Contains メソッドを使用して、文字列 "four" がスタックの最初のコピーにあることを示します。その後で、Clear メソッドがコピーをクリアすると、Count プロパティによってスタックが空であることが示されます。

Imports System
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
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
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ (Int32)

空で、指定した初期量または既定の初期量のうち大きい方の初期量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initialCapacity As Integer _
)
Dim initialCapacity As Integer

Dim instance As New Stack(initialCapacity)
public Stack (
    int initialCapacity
)
public:
Stack (
    int initialCapacity
)
public Stack (
    int initialCapacity
)
public function Stack (
    initialCapacity : int
)

パラメータ

initialCapacity

Stack が格納できる要素数の初期値。

例外例外
例外の種類条件

ArgumentOutOfRangeException

initialCapacity が 0 未満です。

解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ (ICollection)

指定したコレクションからコピーした要素を格納し、コピーされる要素の数と同じ初期量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    col As ICollection _
)
Dim col As ICollection

Dim instance As New Stack(col)
public Stack (
    ICollection col
)
public:
Stack (
    ICollection^ col
)
public Stack (
    ICollection col
)
public function Stack (
    col : ICollection
)

パラメータ

col

要素のコピー元の ICollection。

例外例外
例外の種類条件

ArgumentNullException

col が null 参照 (Visual Basic では Nothing) です。

解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ (ジェネリック IEnumerable)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

指定したコレクションからコピーした要素を格納し、コピーされる要素の数を格納できるだけの容量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections.Generic
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    collection As IEnumerable(Of T) _
)
Dim collection As IEnumerable(Of
 T)

Dim instance As New Stack(Of
 T)(collection)
public Stack (
    IEnumerable<T> collection
)
public:
Stack (
    IEnumerable<T>^ collection
)
public Stack (
    IEnumerable<T> collection
)
public function Stack (
    collection : IEnumerable<T>
)

パラメータ

collection

要素のコピー元のコレクション。

例外例外
例外の種類条件

ArgumentNullException

collection が null 参照 (Visual Basic では Nothing) です。

解説解説

Stack の容量は、Stack が保持できる要素数になります。Stack に要素を追加すると、必要に応じて、内部の配列の再割り当てによって容量が自動的に増加します。

コレクションのサイズを推定できる場合は、初期量を指定すると、Stack に要素を追加するときに、サイズ変更操作を何度も実行する必要がなくなります。

容量を減らすには、TrimExcess を呼び出します。

要素は、コレクションの IEnumerator によって読み取られる順序と同じ順序で、Stack にコピーされます。

このコンストラクタは O(n) 操作です。ここで、n は collection 内の要素数です。

使用例使用例

このコンストラクタおよび Stack ジェネリック クラスのいくつかのメソッドを使用したコード例を次に示します。

このコード例では、既定の容量で文字列のスタックを作成し、Push メソッドを使用して 5 つの文字列をスタックにプッシュします。スタックの要素は列挙されますが、スタックの状態は変化しません。Pop メソッドを使用して、最初の文字列をスタックからポップします。Peek メソッドを使用してスタック内の次の項目を調べてから、Pop メソッドを使用してその項目をスタックからポップします。

ToArray メソッドを使用して配列を作成し、その配列にスタック要素をコピーしてから、IEnumerable を受け取る Stack コンストラクタに配列を渡して、要素の順序を反転したスタックのコピーを作成します。コピーの要素が表示されます。

スタックの 2 倍のサイズの配列が作成され、CopyTo メソッドを使用して配列の中央部で始まる配列要素をコピーします。Stack コンストラクタを再度使用して、要素の順序を反転したスタックのコピーを作成します。その結果、3 つの null 要素が末尾に配置されます。

Contains メソッドを使用して、文字列 "four" がスタックの最初のコピーにあることを示します。その後で、Clear メソッドがコピーをクリアすると、Count プロパティによってスタックが空であることが示されます。

Imports System
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
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
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ (Int32)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

空で、指定した初期量または既定の初期量のうち大きい方の初期量を備えた、Stack クラスの新しいインスタンスを初期化します。

名前空間: System.Collections.Generic
アセンブリ: System (system.dll 内)
構文構文

例外例外
例外の種類条件

ArgumentOutOfRangeException

capacity が 0 未満です。

解説解説

Stack の容量は、Stack が保持できる要素数になります。Stack に要素を追加すると、必要に応じて、内部の配列の再割り当てによって容量が自動的に増加します。

コレクションのサイズを推定できる場合は、初期量を指定すると、Stack に要素を追加するときに、サイズ変更操作を何度も実行する必要がなくなります。

容量を減らすには、TrimExcess を呼び出します。

このコンストラクタは O(n) 操作です。ここで、n は capacity です。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Stack コンストラクタ


Stack コンストラクタ


Stack ジェネリック クラス

メモ : このクラスは、.NET Framework version 2.0 で新しく追加されたものです。

任意の同じ型のインスタンスの、可変サイズの後入れ先出し (LIFO) コレクションを表します。

名前空間: System.Collections.Generic
アセンブリ: System (system.dll 内)
構文構文

<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class Stack(Of T)
    Implements IEnumerable(Of T), ICollection,
 _
    IEnumerable
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class Stack<T> : IEnumerable<T>,
 ICollection, 
    IEnumerable
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename T>
public ref class Stack : IEnumerable<T>,
 ICollection, 
    IEnumerable
J# では、ジェネリックな型およびメソッドは使用できますが、新規に宣言することはできません。
JScript では、ジェネリックな型およびメソッドは使用できません。

型パラメータ

T

スタック内の要素の型を指定します。

解説解説

Stack は、配列として実装されます。

Stack の容量は、Stack が保持できる要素数になります。この実装では、Stack の既定の初期量は 10 ですが、この既定値は将来の .NET Framework SDK のバージョンで変更される可能性があります。Stack に要素を追加すると、必要に応じて、内部の配列の再割り当てによって容量が自動的に増加します。容量を減らすには、TrimExcess を呼び出します。

Count がスタックの容量よりも小さい場合、Push は O(1) 操作になります。新しい要素を格納するために容量を増やす必要がある場合、Push は O(n) 操作になります。ここで、n は Count です。Pop は O(1) 操作です。

Stack は、null 参照 (Visual Basic では Nothing) を参照型に対して有効な値として受け取り、要素の重複を許可します。

使用例使用例

Stack ジェネリック クラスのいくつかのメソッドを使用したコード例を次に示します。このコード例では、既定の容量で文字列のスタックを作成し、Push メソッドを使用して 5 つの文字列をスタックにプッシュします。スタックの要素は列挙されますが、スタックの状態は変化しません。Pop メソッドを使用して、最初の文字列をスタックからポップします。Peek メソッドを使用してスタック内の次の項目を調べてから、Pop メソッドを使用してその項目をスタックからポップします。

ToArray メソッドを使用して配列を作成し、その配列にスタック要素をコピーしてから、IEnumerable を受け取る Stack コンストラクタに配列を渡して、要素の順序を反転したスタックのコピーを作成します。コピーの要素が表示されます。

スタックの 2 倍のサイズの配列が作成され、CopyTo メソッドを使用して配列の中央部で始まる配列要素をコピーします。Stack コンストラクタを再度使用して、要素の順序を反転したスタックのコピーを作成します。その結果、3 つの null 要素が末尾に配置されます。

Contains メソッドを使用して、文字列 "four" がスタックの最初のコピーにあることを示します。その後で、Clear メソッドがコピーをクリアすると、Count プロパティによってスタックが空であることが示されます。

Imports System
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
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
 */
継承階層継承階層
System.Object
  System.Collections.Generic.Stack
スレッド セーフスレッド セーフ

この型の public static (Visual Basic では Shared) メンバは、スレッド セーフです。すべてのインスタンス メンバがスレッド セーフになるかどうかは保証されていません。

コレクションが変更されない限り、Stack では、複数の読み込み操作が同時に発生しても問題ありません。ただし、コレクションの列挙処理は、本質的にはスレッド セーフな処理ではありません。すべての列挙処理が終わるまでコレクションをロックすることにより、列挙処理でのスレッド セーフを確保できます。コレクションに対し複数のスレッドがアクセスして読み取りや書き込みを行うことができるようにするには、独自に同期化を実装する必要があります。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Stack メンバ
System.Collections.Generic 名前空間

Stack プロパティ


パブリック プロパティパブリック プロパティ

  名前 説明
パブリック プロパティ SyncRoot Stack へのアクセスを同期するために使用できるオブジェクトを取得します。
参照参照

関連項目

Stack クラス
System.Collections 名前空間
System.Collections.Generic.Stack

Stack プロパティ


パブリック プロパティパブリック プロパティ

  名前 説明
パブリック プロパティ Count Stack に格納されている要素の数を取得します。
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.Collections.ICollection.SyncRoot ICollection へのアクセスを同期するために使用できるオブジェクトを取得します。
参照参照

関連項目

Stack ジェネリック クラス
System.Collections.Generic 名前空間

Stack メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Clear Stack からすべてのオブジェクトを削除します。
パブリック メソッド Contains ある要素が Stack 内に存在するかどうかを判断します。
パブリック メソッド CopyTo 既存の 1 次元の Array に Stack をコピーします。コピー操作は、配列の指定したインデックスから始まります。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetEnumerator Stack の列挙子を返します。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド Peek Stack の先頭にあるオブジェクトを削除せずに返します。
パブリック メソッド Pop Stack の先頭にあるオブジェクトを削除し、返します。
パブリック メソッド Push Stack の先頭にオブジェクトを挿入します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド ToArray Stack を新しい配列にコピーします。
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
パブリック メソッド TrimExcess Stack 内にある実際の要素数が現在の容量の 90% 未満の場合は、容量をその数に設定します。
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.Collections.Generic.IEnumerable<T>.GetEnumerator コレクションを反復処理する列挙子を返します。
インターフェイスの明示的な実装 System.Collections.ICollection.CopyTo ICollection の要素を Array にコピーします。Array の特定のインデックスからコピーが開始されます。
インターフェイスの明示的な実装 System.Collections.IEnumerable.GetEnumerator コレクションを反復処理する列挙子を返します。
参照参照

関連項目

Stack ジェネリック クラス
System.Collections.Generic 名前空間

Stack メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Clear Stack からすべてのオブジェクトを削除します。
パブリック メソッド Clone Stack の簡易コピーを作成します。
パブリック メソッド Contains ある要素が Stack 内に存在するかどうかを判断します。
パブリック メソッド CopyTo 既存の 1 次元の Array に Stack をコピーします。コピー操作は、配列の指定したインデックスから始まります。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetEnumerator Stack の IEnumerator を返します。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド Peek Stack の先頭にあるオブジェクトを削除せずに返します。
パブリック メソッド Pop Stack の先頭にあるオブジェクトを削除し、返します。
パブリック メソッド Push Stack の先頭にオブジェクトを挿入します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Synchronized Stack 用の同期された (スレッド セーフな) ラッパーを返します。
パブリック メソッド ToArray Stack を新しい配列にコピーします。
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Stack クラス
System.Collections 名前空間
System.Collections.Generic.Stack

Stack メンバ

任意の同じ型のインスタンスの、可変サイズの後入れ先出し (LIFO) コレクションを表します。

Stack ジェネリック型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
  名前 説明
パブリック プロパティ Count Stack に格納されている要素の数を取得します。
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Clear Stack からすべてのオブジェクトを削除します。
パブリック メソッド Contains ある要素が Stack 内に存在するかどうかを判断します。
パブリック メソッド CopyTo 既存の 1 次元の Array に Stack をコピーします。コピー操作は、配列の指定したインデックスから始まります。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetEnumerator Stack の列挙子を返します。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド Peek Stack の先頭にあるオブジェクトを削除せずに返します。
パブリック メソッド Pop Stack の先頭にあるオブジェクトを削除し、返します。
パブリック メソッド Push Stack の先頭にオブジェクトを挿入します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド ToArray Stack を新しい配列にコピーします。
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
パブリック メソッド TrimExcess Stack 内にある実際の要素数が現在の容量の 90% 未満の場合は、容量をその数に設定します。
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.Collections.Generic.IEnumerable<T>.GetEnumerator コレクションを反復処理する列挙子を返します。
インターフェイスの明示的な実装 System.Collections.ICollection.CopyTo ICollection の要素を Array にコピーします。Array の特定のインデックスからコピーが開始されます。
インターフェイスの明示的な実装 System.Collections.IEnumerable.GetEnumerator コレクションを反復処理する列挙子を返します。
インターフェイスの明示的な実装 System.Collections.ICollection.SyncRoot ICollection へのアクセスを同期するために使用できるオブジェクトを取得します。
参照参照

関連項目

Stack ジェネリック クラス
System.Collections.Generic 名前空間

Stack メンバ

オブジェクトの単純な後入れ先出し (LIFO) 非ジェネリック コレクションを表します。

Stack データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
  名前 説明
パブリック プロパティ SyncRoot Stack へのアクセスを同期するために使用できるオブジェクトを取得します。
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Clear Stack からすべてのオブジェクトを削除します。
パブリック メソッド Clone Stack の簡易コピーを作成します。
パブリック メソッド Contains ある要素が Stack 内に存在するかどうかを判断します。
パブリック メソッド CopyTo 既存の 1 次元の Array に Stack をコピーします。コピー操作は、配列の指定したインデックスから始まります。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetEnumerator Stack の IEnumerator を返します。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド Peek Stack の先頭にあるオブジェクトを削除せずに返します。
パブリック メソッド Pop Stack の先頭にあるオブジェクトを削除し、返します。
パブリック メソッド Push Stack の先頭にオブジェクトを挿入します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド Synchronized Stack 用の同期された (スレッド セーフな) ラッパーを返します。
パブリック メソッド ToArray Stack を新しい配列にコピーします。
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Stack クラス
System.Collections 名前空間
System.Collections.Generic.Stack

Stack

ポーカーテーブルにおいて、自分がもっている金額 (即ち自分の前にあるstack of chips(チップの山))。時に複数形で使われる。short stack(ショートスタック)も参考のこと。
stack(スタック)は、特定の数のチップを指すこともある。ほとんどのchip racks(チップラック)は、20枚を1スタックの形で収容するタイプのものである。プレーヤーの中には、自分のチップを好みの大きさのスタックにして並べている人も多い。私(Dan)は、10チップのスタックが好きであるが、20とか30チップのスタックにしている人が多いようである。

I was doing well earlier, but my stacks have been dwindling.
(最初は好調だったんだけど、チップの量はほとんど変化せずそのままだねえ)。

Stack

名前 スタック

スタック (曖昧さ回避)

(Stack から転送)

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2025/01/06 05:33 UTC 版)

スタック、スタッキング

stack

stuck

脚注

  1. ^ “stuck”. weblio. 2023年1月23日閲覧。

関連項目


stack

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2019/04/29 13:43 UTC 版)

「Standard Template Library」の記事における「stack」の解説

スタック。(FILO; First In, Last Out)

※この「stack」の解説は、「Standard Template Library」の解説の一部です。
「stack」を含む「Standard Template Library」の記事については、「Standard Template Library」の概要を参照ください。

ウィキペディア小見出し辞書の「Stack」の項目はプログラムで機械的に意味や本文を生成しているため、不適切な項目が含まれていることもあります。ご了承くださいませ。 お問い合わせ。


英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

「Stack」の関連用語

Stackのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Stackのページの著作権

   
デジタル大辞泉デジタル大辞泉
(C)Shogakukan Inc.
株式会社 小学館
IT用語辞典バイナリIT用語辞典バイナリ
Copyright © 2005-2026 Weblio 辞書 IT用語辞典バイナリさくいん。 この記事は、IT用語辞典バイナリの【スタック】の記事を利用しております。
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.
日本ポーカープレーヤーズ協会日本ポーカープレーヤーズ協会
日本ポーカープレーヤーズ協会 All Rights Reserved
日外アソシエーツ株式会社日外アソシエーツ株式会社
Copyright (C) 1994- Nichigai Associates, Inc., All rights reserved.
ウィキペディアウィキペディア
All text is available under the terms of the GNU Free Documentation License.
この記事は、ウィキペディアのスタック (曖昧さ回避) (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。 Weblio辞書に掲載されているウィキペディアの記事も、全てGNU Free Documentation Licenseの元に提供されております。
ウィキペディアウィキペディア
Text is available under GNU Free Documentation License (GFDL).
Weblio辞書に掲載されている「ウィキペディア小見出し辞書」の記事は、WikipediaのStandard Template Library (改訂履歴)、スタック (曖昧さ回避) (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。

©2026 GRAS Group, Inc.RSS