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
广告