PHP - Ds Stack::allocate() 函式



PHP 的 Ds\Stack::allocate() 函式用於為所需容量分配足夠的記憶體。棧的容量是指棧可以容納的記憶體或元素數量。

如果指定的容量小於當前棧的大小,則容量不會減小,或者舊的容量將保持不變。您可以使用 capacity() 函式檢查棧的當前容量。

語法

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

public Ds\Stack::allocate(int $capacity): void

引數

以下是此函式的引數:

  • capacity - 應該為此棧分配容量的值的數量。

返回值

此函式不返回值。

示例 1

以下程式演示了 PHP Ds\Stack::allocate() 函式的使用:

<?php
   $stack = new \Ds\Stack([1, 2, 3]);
   echo "The stack elements are: \n";
   print_r($stack);
   $capacity = 20;
   echo "The capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

輸出

上述程式產生以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
The capacity needs to be allocated: 20
The new capacity of stack after allocated: 20

示例 2

以下是 PHP Ds\Stack::allocate() 函式的另一個示例。我們使用此函式為該棧 (["Tutorials", "Point", "India"]) 的所需容量分配 32 的記憶體:

<?php
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The initial capacity of this stack is: ";
   print_r($stack->capacity());
   $capacity = 32;
   echo "\nThe capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The initial capacity of this stack is: 8
The capacity needs to be allocated: 32
The new capacity of stack after allocated: 32

示例 3

如果指定的容量小於棧的當前容量,則舊的容量將不會更改。

<?php
   $stack = new \Ds\Stack(['a', 'e', 'i', 'o', 'u']);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The initial capacity of this stack is: ";
   print_r($stack->capacity());
   $capacity = 5;
   echo "\nThe capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

輸出

執行上述程式後,它將生成以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
The initial capacity of this stack is: 8
The capacity needs to be allocated: 5
The new capacity of stack after allocated: 8
php_function_reference.htm
廣告