PHP - Ds Map::capacity() 函式



PHP 的 Ds\Map::capacity() 函式用於檢索對映的當前容量。此函式還返回其他集合(例如 PHP Ds 擴充套件中的“集合”或“雙端佇列”)的當前容量。

容量表示對映的內部記憶體分配,它決定了對映可以有效容納多少元素。您還可以使用 allocate() 函式顯式分配自定義容量。

假設您向對映新增更多元素並超過其當前容量,它將自動為新元素分配更多記憶體。

語法

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

public Ds\Map::capacity(): int

引數

此函式不接受任何引數。

返回值

此函式返回對映的當前容量。

示例 1

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

<?php  
   $map = new \Ds\Map();
   echo "The map elements are: ";
   print_r($map);
   echo "The current capacity of this map: ";
   #using capacity() function
   print_r($map->capacity());
?>

輸出

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

The map elements are: Ds\Map Object
(
)
The current capacity of this map: 8

示例 2

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

<?php  
   $map = new \Ds\Map([10, 20, 30]);
   echo "The map elements are: \n";
   foreach ($map as $key => $value) {
       echo "[".$key."] => ".$value."\n";
   }
   echo "The capacity of this map (initial): ";
   #using the capacity() function
   print_r($map->capacity());
   #using the allocate() function
   $map->allocate(64);
   echo "\nThe capacity of this map after allocating new capacity: ";
   print_r($map->capacity());
?>

輸出

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

The map elements are:
[0] => 10
[1] => 20
[2] => 30
The capacity of this map (initial): 8
The capacity of this map after allocating new capacity: 64
php_function_reference.htm
廣告