PHP - Ds Vector::capacity() 函式



PHP 的 Ds\Vector::capacity() 函式用於檢索向量的當前容量。向量的容量是指向量可以佔據的記憶體或元素數量。

Ds\Vector 類提供了另一個名為 allocate() 的內建函式。使用此函式,您可以為當前向量分配新的容量。

語法

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

public int Ds\Vector::capacity( void )

引數

此函式不接受任何引數。

返回值

此函式返回向量的當前容量。

示例 1

以下是 PHP Ds\Vector::capacity() 函式的基本示例:

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The current capacity of a vector: ";
   var_dump($vector->capacity());	 
?>

輸出

以上程式產生以下輸出:

The vector elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The current capacity of a vector: int(8)

示例 2

以下是 PHP Ds\Vector::capacity() 函式的另一個示例。我們使用此函式在分配此向量 (["Tutorials", "Point", "India"]) 的新容量之前和之後檢索容量:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The initial capacity of a vector: ";
   print_r($vector->capacity());
   echo "\nAfter allocating new capacity is: ";
   $vector->allocate(64);
   print_r($vector->capacity());
?> 

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The initial capacity of a vector: 8
After allocating new capacity is: 64

示例 3

在下面的示例中,我們使用 capacity() 函式來檢索空 ([]) 向量的容量:

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

輸出

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

The vector elements are:
Ds\Vector Object
(
)
The capacity of a vector: 8
php_function_reference.htm
廣告