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



PHP 的 Ds\PriorityQueue::push() 函式用於將具有給定優先順序的數值壓入佇列。此函式不返回值,而是透過新增新元素來修改優先順序佇列。

語法

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

public void Ds\PriorityQueue::push( mixed $value , int $priority )

引數

以下是 push() 函式的引數:

  • $value - 要新增到佇列中的值。

  • $priority - 與值關聯的優先順序。可以是整數或浮點數。

返回值

push() 函式不返回任何值。優先順序佇列將透過新增新元素進行更新。

PHP 版本

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

示例 1

首先,我們將向您展示 PHP Ds\PriorityQueue::push() 函式向優先順序佇列新增元素的基本示例。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  
   $pqueue->push("Tutorials", 1); 
   $pqueue->push("Point", 2); 
   $pqueue->push("India", 3); 
  
   echo "The PriorityQueue is: \n"; 
   print_r($pqueue);
?>

輸出

以上程式碼將產生類似於以下的結果:

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

示例 2

在這裡,我們將使用 push() 函式新增具有不同優先順序的待辦事項。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   
   // Push elements with different priorities
   $pqueue->push("Clean the house", 1);
   $pqueue->push("Finish homework", 5);
   $pqueue->push("Go shopping", 3);
   
   // Print the queue
   foreach ($pqueue as $task) {
       echo $task . "\n";
   }
?> 

輸出

這將生成以下輸出:

Finish homework
Go shopping
Clean the house

示例 3

現在,我們將使用浮點數作為不同的優先順序,並使用 push() 函式向 PriorityQueue 新增新元素。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   
   // Push elements with float priorities
   $pqueue->push("Read a book", 2.5);
   $pqueue->push("Play games", 1.2);
   $pqueue->push("Exercise", 3.7);
   
   // Print the queue
   foreach ($pqueue as $activity) {
       echo $activity . "\n";
   }
?> 

輸出

這將建立以下輸出:

Exercise
Read a book
Play games

示例 4

在下面的示例中,我們使用 push() 函式向優先順序佇列新增新專案並處理相同優先順序的情況。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   
   // Push elements with the same priority
   $pqueue->push("Task A", 2);
   $pqueue->push("Task B", 2);
   $pqueue->push("Task C", 2);
   
   // Print the queue
   foreach ($pqueue as $task) {
       echo $task . "\n";
   }
?> 

輸出

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

Task A
Task B
Task C
php_function_reference.htm
廣告