PHP - Ds Deque::insert() 函式



PHP 的 Ds\Deque::insert() 函式用於在指定索引處的當前雙端佇列中插入一個值。索引是雙端佇列中元素的位置,從 0 開始表示第一個元素,1 表示第二個元素,依此類推。

如果指定的索引值無效,這意味著負數或大於雙端佇列的大小,它將丟擲“OutOfRangeException”異常。

語法

以下是 PHP Ds\Deque::insert() 函式的語法 -

public Ds\Deque::insert(int $index, mixed ...$values): void 

引數

以下是此函式的引數 -

  • index - 它表示一個整數,指定要插入的索引。
  • values - 需要插入的整數值。

返回值

此函式不返回任何值;相反,它將值插入到雙端佇列中。

示例 1

以下是 PHP Ds\Deque::insert() 函式的基本示例 -

<?php
   $deque = new \Ds\Deque([2, 3, 4, 5]);
   echo "The deque elements are: \n";
   print_r($deque);
   $index = 0;
   $value = 1;
   echo "The given index and value is: ".$index.", ".$value;
   echo "\nThe deque after a new element is inserted: ";
   #using insert() function
   $deque->insert($index, $value);
   print_r($deque);
?>

輸出

以上程式顯示以下輸出 -

The deque elements are:
Ds\Deque Object
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
)
The given index and value is: 0, 1
The deque after a new element is inserted: Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

示例 2

以下是 PHP Ds\Deque::insert() 函式的另一個示例。我們使用此函式在此雙端佇列 ([10, 20, 30, 50]) 中的指定索引 3 處插入值 40 -

<?php
   $deque = new \Ds\Deque(["Tutorials", "Point"]);
   echo "The elements of deque: \n";
   print_r($deque);
   $index = 2;
   $value = "India";
   echo "The given index and value is: ".$index.", ".$value;
   echo "\nThe deque after new elements inserted: \n";
   #using insert() function
   $deque->insert($index, $value);
   print_r($deque);
?>

輸出

執行上述程式後,將生成以下輸出 -

The elements of deque:
Ds\Deque Object
(
    [0] => Tutorials
    [1] => Point
)
The given index and value is: 2, India
The deque after new elements inserted:
Ds\Deque Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)

示例 3

如果指定的 index 值“大於”雙端佇列的大小,此函式將丟擲 “OutOfRangeException”,如下所示 -

<?php
   $deque = new \Ds\Deque([10, 20, 30, 40]);
   echo "The original deque: \n";
   print_r($deque);
   $index = 5;
   $val = 50;
   echo "The given and value is: ".$index.", ".$val;
   echo "\nThe deque after inserting new value: \n";
   $deque->insert($index, $val);
   print_r($deque);
?>

輸出

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

The original deque:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)
The given and value is: 5, 50
The deque after inserting new value:
PHP Fatal error:  Uncaught OutOfRangeException: Index out of range: 
5, expected 0 <= x <= 3 in C:\Apache24\htdocs\index.php:9
Stack trace:
#0 C:\Apache24\htdocs\index.php(9): Ds\Deque->insert(5, 50)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 9
php_function_reference.htm
廣告