PHP - Ds\Queue::allocate() 函式



PHP 的Ds\Queue::allocate() 函式用於為佇列的指定容量分配記憶體。“容量”指的是佇列可以容納的元素數量。

如果指定的容量小於當前容量(例如,負數),則當前容量保持不變,不會為佇列分配新的記憶體。可以使用 capacity() 函式檢查佇列的當前容量。

語法

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

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

引數

此函式接受一個引數,如下所述:

  • capacity - 需要分配容量的值的數量。

返回值

此函式不返回任何值。

示例 1

以下是 PHP Ds\Queue::allocate() 的基本示例:

<?php  
   $queue = new \Ds\Queue([1, 2, 3, 4, 5]);
   echo "The queue elements are: \n";
   print_r($queue);
   #using allocate() function
   $queue->allocate(50);
   echo "Capacity of this queue: ".$queue->capacity();
?>

輸出

上述程式輸出如下:

The queue elements are:
Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Capacity of this queue: 64

示例 2

以下是 PHP Ds\Queue::allocate() 函式的另一個示例。我們使用此函式為所需的容量分配足夠的記憶體100

<?php  
   $queue = new \Ds\Queue(['a', 'e', 'i', 'o', 'u']);
   echo "The queue elements are: \n";
   print_r($queue);
   echo "The current capacity before allocated: ";
   print_r($queue->capacity());
   $new_cap = 100;
   echo "\nThe capacity need to allocate: $new_cap";
   #using allocate() function
   $queue->allocate($new_cap);
   echo "\nThe Capacity after allocated: ".$queue->capacity();
?>

輸出

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

The queue elements are:
Ds\Queue Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The current capacity before allocated: 8
The capacity need to allocate: 100
The Capacity after allocated: 128

示例 3

如果指定的容量小於或等於當前容量,則容量將保持不變,此函式將不做任何操作:

<?php  
   $queue = new \Ds\Queue(["Tutorials", "Point", "India"]);
   echo "The queue elements are: \n";
   print_r($queue);
   echo "The current capacity before allocated: ";
   print_r($queue->capacity());
   $new_cap = -10;
   echo "\nThe capacity need to allocate: $new_cap";
   #using allocate() function
   $queue->allocate($new_cap);
   echo "\nThe Capacity after allocated: ".$queue->capacity();
?>

輸出

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

The queue elements are:
Ds\Queue Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The current capacity before allocated: 8
The capacity need to allocate: -10
The Capacity after allocated: 8
php_function_reference.htm
廣告