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



PHP 的 Ds\Queue::capacity() 函式用於檢索佇列的當前容量。“容量”指的是佇列可以容納的元素數量。

PHP Ds\Queue 類提供了另一個名為 allocate() 的函式,您可以使用它為所需的容量分配足夠的記憶體。

語法

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

public Ds\Queue::capacity(): int

引數

此函式不接受任何引數。

返回值

此函式返回佇列的當前容量。

示例 1

以下程式演示了 PHP Ds\Queue::capacity() 函式的用法:

<?php  
   $queue = new \Ds\Queue([10, 20, 30]);
   echo "The queue elements are: \n";
   print_r($queue);
   echo "The current capacity of a queue: ";
   #using capacity() function   
   print_r($queue->capacity());
?>

輸出

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

The queue elements are:
Ds\Queue Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
The current capacity of a queue: 8

示例 2

以下是 PHP Ds\Queue::capacity() 函式的另一個示例。我們使用此函式檢索此佇列 (['a', 'b', 'c', 'd']) 的當前容量:

<?php  
   $queue = new \Ds\Queue(['a', 'b', 'c', 'd']);
   echo "The queue elements are: \n";
   print_r($queue);
   echo "The current capacity before allocating new one: ";
   #using capacity() function   
   print_r($queue->capacity());
   echo "\nThe current capacity after allocating new one: ";
   $queue->allocate(16);   
   print_r($queue->capacity());
?>

輸出

上述程式提供以下輸出:

The queue elements are:
Ds\Queue Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
The current capacity before allocating new one: 8
The current capacity after allocating new one: 16

示例 3

檢索空佇列 ([""]) 的容量:

<?php  
   $queue = new \Ds\Queue([""]);
   echo "The queue elements are: \n";
   print_r($queue);
   echo "The current capacity of a queue: ";
   print_r($queue->capacity());
?>

輸出

以下是上述程式的輸出:

The queue elements are:
Ds\Queue Object
(
    [0] =>
)
The current capacity of a queue: 8
php_function_reference.htm
廣告