PHP - Ds Stack::capacity() 函式



PHP 的 Ds\Stack::capacity() 函式用於檢索棧的當前容量。棧的容量是指棧可以佔用的記憶體或元素數量。

您可以使用 allocate() 函式為當前棧分配新的容量。

語法

以下是 PHP Ds\Stack::capacity() 函式的語法:

public Ds\Stack::capacity(): int

引數

此函式不接受任何引數。

返回值

此函式返回棧的當前容量。

示例 1

以下是 PHP Ds\Stack::capacity() 函式的基本示例:

<?php
   $stack = new \Ds\Stack(['a', 'e', 'i', 'o', 'u']);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The capacity of the stack is: ";
   print_r($stack->capacity());
?>

輸出

以上程式產生以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
The capacity of the stack is: 8

示例 2

使用 allocate() 函式分配 新容量

以下是 PHP Ds\Stack::capacity() 函式的另一個示例。我們使用此函式檢索此棧 ([10, 20, 30, 40, 50]) 的當前容量:

<?php
   $stack = new \Ds\Stack([10, 20, 30, 40, 50]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The initial capacity of the stack is: ";
   print_r($stack->capacity());
   echo "\nAfter allocating new capacity the stack capacity is: ";
   #using allocate() function
   $stack->allocate(64);
   print_r($stack->capacity());
?>

輸出

執行以上程式後,將顯示以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => 50
    [1] => 40
    [2] => 30
    [3] => 20
    [4] => 10
)
The initial capacity of the stack is: 8
After allocating new capacity the stack capacity is: 64

示例 3

在下面的示例中,我們使用 capacity() 函式檢索空棧 ([]) 的當前容量:

<?php
   $stack = new \Ds\Stack([]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The current capacity of the stack is: ";
   print_r($stack->capacity());
?>

輸出

執行以上程式後,將顯示以下輸出:

The stack elements are:
Ds\Stack Object
(
)
The current capacity of the stack is: 8
php_function_reference.htm
廣告