Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Vector::capacity() Function



The PHP Ds\Vector::capacity() function is used to retrieve the current capacity of a vector. The capacity of the vector is the memory or the number of elements that the vector can occupy.

The Ds\Vector class provides another built-in function named allocate(). Using this function, you can allocate a new capacity for the current vector.

Syntax

Following is the syntax of the PHP Ds\Vector::capacity() function −

public int Ds\Vector::capacity( void )

Parameters

This function does not accept any parameter.

Return value

This function returns the current capacity of a vector.

Example 1

The following is the basic example of the PHP Ds\Vector::capacity() function −

<?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());	 
?>

Output

The above program produces the following output −

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)

Example 2

Following is another example of the PHP Ds\Vector::capacity() function. We use this function to retrieve the capacity before and after allocating a new capacity of this vector (["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());
?> 

Output

After executing the above program, the following output will be displayed −

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

Example 3

In the example below, we are using the capacity() function to retrieve the capacity of an empty ([]) vector −

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

Output

Once the above program is executed, it will display the following output −

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