PHP - Ds\PriorityQueue::peek() 函式



PHP 的 **Ds\PriorityQueue::peek()** 函式用於返回佇列前端的值。此函式返回此 PriorityQueue 前端的值。函式的混合返回型別由 PriorityQueue 中儲存的值的型別決定。

語法

以下是 PHP **Ds\PriorityQueue::peek()** 函式的語法:

public mixed Ds\PriorityQueue::peek( void )

引數

**peek()** 函式沒有任何引數。

返回值

此函式返回佇列前端的值,但不將其移除。

異常

如果 PriorityQueue 為空,則 **peek()** 函式將丟擲 UnderflowException。

PHP 版本

**peek()** 函式從 Ds 擴充套件的 1.0.0 版本開始可用。

示例 1

首先,我們將向您展示 PHP **Ds\PriorityQueue::peek()** 函式的基本示例,以獲取佇列前端的值。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue(); 
   
   // Push the elements
   $pqueue->push("Tutorials", 1); 
   $pqueue->push("Point", 2); 
   $pqueue->push("India", 3); 
  
   echo "The PriorityQueue is: \n"; 
   print_r($pqueue); 
   
   echo "\nThe element at front of queue is: "; 
   print_r($pqueue->peek()); 
?>

輸出

以上程式碼將產生類似這樣的結果:

The PriorityQueue is: 
Ds\PriorityQueue Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)

The element at front of queue is: India

示例 2

現在,我們將使用佇列元素中不同優先順序的不同資料型別,並使用 **peek()** 函式獲取佇列前端的值。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();

   $pqueue->push(100, 5);
   $pqueue->push("String", 2);
   $pqueue->push([1, 2, 3], 8);
   
   $topElement = $pqueue->peek();
   
   if (is_array($topElement)) {
       echo 'Array: ';
       print_r($topElement);
   } else {
       echo $topElement;
   }
?> 

輸出

這將生成以下輸出:

Array: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

示例 3

在以下示例中,我們使用 **peek()** 函式查詢佇列中的 peek 元素,但這裡我們使用負數作為優先順序。因此,在示例中,-1 高於 -5 和 -10。

<?php
   // Create a new PriorityQueue
   $queue = new \Ds\PriorityQueue();

   $queue->push("Low Priority", -1);
   $queue->push("Medium Priority", -5);
   $queue->push("High Priority", -10);
   
   echo $queue->peek(); 
?> 

輸出

以下是上述程式碼的輸出:

Low Priority

示例 4

現在,在下面的程式碼中,我們使用整數作為優先順序,並使用自定義物件作為元素。

<?php
   // Define class here
   class Task {
      public $name;
      public function __construct($name) {
          $this->name = $name;
      }
  }
  
  $pqueue = new \Ds\PriorityQueue();
  
  $pqueue->push(new Task("Task 1"), 10);
  $pqueue->push(new Task("Task 2"), 20);
  $pqueue->push(new Task("Task 3"), 5);
  
  $highestPriorityTask = $pqueue->peek();
  echo $highestPriorityTask->name;
?> 

輸出

這將建立以下輸出:

Task 2
php_function_reference.htm
廣告