PHP - Ds Vector::allocate() 函式



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

如果向量的當前容量大於分配的容量,則舊容量保持不變,並且不會分配新容量。您可以使用 capacity() 函式來檢查向量的當前容量。

語法

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

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

引數

此函式接受一個名為 'capacity' 的引數,該引數儲存需要分配的新容量值。

返回值

此函式不返回值。

示例 1

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

<?php 
   $vector = new \Ds\Vector([10, 20, 30]);
   echo "The vector elements are: \n";
   print_r($vector);
   $capacity = 20;
   echo "The capacity need to allocate: ".$capacity;
   $vector->allocate($capacity);
   echo "\nAfter allocating capacity is: ";
   print_r($vector->capacity());
?>

輸出

上述程式顯示以下輸出:

The vector elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
The capacity need to allocate: 20
After allocating capacity is: 20

示例 2

以下是 PHP Ds\Vector::allocate() 函式的另一個示例。我們使用此函式為此向量(["Tutorials", "Point", "India"])分配容量 “32”

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "Capacity before allocating: ";
   print_r($vector->capacity());
   $capacity = 32;
   echo "\nThe capacity need to allocate: ".$capacity;
   echo "\nThe allocated capacity: ";
   $vector->allocate($capacity);
   print_r($vector->capacity());
?>

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
Capacity before allocating: 8
The capacity need to allocate: 32
The allocated capacity: 32

示例 3

如果指定的容量 小於向量的當前容量,則舊容量將保持不變,並且不會為向量分配新容量:

<?php 
   $vector = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo "The vector elements are: \n";
   print_r($vector);
   $capacity = 5;
   echo "The capacity need to allocate: ".$capacity;
   $vector->allocate($capacity);
   echo "\nAfter allocating a new capacity is: ";
   print_r($vector->capacity());
?>

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The capacity need to allocate: 5
After allocating a new capacity is: 8
php_function_reference.htm
廣告