PHP - Ds Deque::get() 函式



PHP 的Ds\Deque::get()函式用於從雙端佇列中檢索指定索引處的元素。“索引”是雙端佇列中元素的位置,從0開始,表示第一個元素,1表示第二個元素,以此類推。

如果指定的索引無效(即為負數或大於雙端佇列的大小),則此函式將丟擲“OutOfRangeException”異常。

語法

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

public Ds\Deque::get(int $index): mixed 

引數

此函式接受一個名為“index”的引數,如下所述:

  • index - 一個基於0的索引,用於查詢元素。

返回值

此函式返回指定索引處的元素。

示例 1

以下程式演示了PHP Ds\Deque::get() 函式的使用:

<?php
   $deque = new \Ds\Deque([10, 20, 30, 40, 50]);
   echo "The deque elements are: \n";
   print_r($deque);
   $index = 0;
   echo "The index value is: ".$index;
   echo "\nThe element at index ".$index." is: ";
   #using get() function
   print_r($deque->get($index));
?>

輸出

上述程式返回第3個索引的元素為:

The deque elements are:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The index value is: 0
The element at index 0 is: 10

示例 2

以下是PHP Ds\Deque::get() 函式的另一個示例。我們使用此函式來檢索此雙端佇列(["Tutorials", "Point", "India", "Tutorix"])中指定索引0處的元素:

<?php
   $deque = new \Ds\Deque(["Tutorials", "Point", "India", "Tutorix"]);
   echo "The deque elements are: ";
   print_r($deque);
   $index = 0;
   echo "The given index is: ".$index;
   echo "\nThe element find at index ".$index." is: ";
   var_dump($deque->get($index));
?>

輸出

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

The deque elements are: Ds\Deque Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
    [3] => Tutorix
)
The given index is: 0
The element find at index 0 is: string(9) "Tutorials"

示例 3

如果指定的索引值為-1,此函式將丟擲“OutOfRangeException”異常。

在下面的示例中,我們使用PHP Ds\Deque::get() 函式來檢索此雙端佇列([1, 1, 2, 3, 5])中指定索引-1處的元素:

<?php
   $deque = new \Ds\Deque([1, 2, 3, 4, 5]);
   echo "The deque elements are: \n";
   print_r($deque);
   $index = -1;
   echo "The given index is: ".$index;
   echo "\nThe element at index ".$index." is: /n";
   print_r($deque->get($index));
?>

輸出

執行上述程式後,將丟擲以下異常:

The deque elements are:
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The given index is: -1
The element at index -1 is: /nPHP Fatal error:  Uncaught OutOfRangeException: 
Index out of range: -1, expected 0 <= x <= 4 in C:\Apache24\htdocs\index.php:8
Stack trace:
#0 C:\Apache24\htdocs\index.php(8): Ds\Deque->get(-1)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 8
php_function_reference.htm
廣告