PHP - Ds Stack::allocate() 函数



PHP 的 Ds\Stack::allocate() 函数用于为所需容量分配足够的内存。栈的容量是指栈可以容纳的内存或元素数量。

如果指定的容量小于当前栈的大小,则容量不会减小,或者旧的容量将保持不变。您可以使用 capacity() 函数检查栈的当前容量。

语法

以下是 PHP Ds\Stack::allocate() 函数的语法:

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

参数

以下是此函数的参数:

  • capacity - 应该为此栈分配容量的值的数量。

返回值

此函数不返回值。

示例 1

以下程序演示了 PHP Ds\Stack::allocate() 函数的使用:

<?php
   $stack = new \Ds\Stack([1, 2, 3]);
   echo "The stack elements are: \n";
   print_r($stack);
   $capacity = 20;
   echo "The capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

输出

上述程序产生以下输出:

The stack elements are:
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
The capacity needs to be allocated: 20
The new capacity of stack after allocated: 20

示例 2

以下是 PHP Ds\Stack::allocate() 函数的另一个示例。我们使用此函数为该栈 (["Tutorials", "Point", "India"]) 的所需容量分配 32 的内存:

<?php
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The initial capacity of this stack is: ";
   print_r($stack->capacity());
   $capacity = 32;
   echo "\nThe capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

输出

执行上述程序后,将显示以下输出:

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The initial capacity of this stack is: 8
The capacity needs to be allocated: 32
The new capacity of stack after allocated: 32

示例 3

如果指定的容量小于栈的当前容量,则旧的容量将不会更改。

<?php
   $stack = new \Ds\Stack(['a', 'e', 'i', 'o', 'u']);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The initial capacity of this stack is: ";
   print_r($stack->capacity());
   $capacity = 5;
   echo "\nThe capacity needs to be allocated: ".$capacity;
   #using allocate() function
   $stack->allocate($capacity);
   echo "\nThe new capacity of stack after allocated: ";
   print_r($stack->capacity());
?>

输出

执行上述程序后,它将生成以下输出:

The stack elements are:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
The initial capacity of this stack is: 8
The capacity needs to be allocated: 5
The new capacity of stack after allocated: 8
php_function_reference.htm
广告