普通的隊列是一種先進先出的數據結構,元素在隊列尾追加,而從隊列頭取出。在優先隊列中,元素被賦予優先級。當訪問元素時,具有最高優先級的元素最先取出。優先隊列具有最高級先出 (largest-in,first-out)的行為特征。
總結下來就是普通隊列有**先進先出**原則,優先級隊列有**優先級高先出**原則,這個優先級可以設置;
## 類摘要
```php
// 1. 沒有實現ArrayAccess接口,所以不能像數組那樣操作;
SplPriorityQueue implements Iterator , Countable {
/* 方法 */
public __construct ( void )
// 比較方法,內部應該用到了冒泡排序,對于權重值來說,返回0代表相等,返回正整數就代表大于,返回負整數就代表小于;
// 默認是權重值越優先,也可以讓其被子類覆蓋改為權重值越小越優先
public int compare ( mixed $priority1 , mixed $priority2 )
public mixed extract ( void )
//恢復到上一個被破壞的節點? 測試無用;
public void recoverFromCorruption ( void )
public void setExtractFlags ( int $flags )
public void insert ( mixed $value , mixed $priority )
public int count ( void )
public mixed current ( void )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public mixed top ( void )
public bool valid ( void )
}
```
## Example
```php
class PQtest extends SplPriorityQueue
{
//覆蓋父類,更改其優先規則為權重值越小越優先;
public function compare($priority1, $priority2)
{
if ($priority1 === $priority2) return 0;
return $priority1 > $priority2 ? -1 : 1;
}
}
$pq = new PQtest();
// 設置值與優先值
$pq->insert('a', 10);
$pq->insert('b', 1);
$pq->insert('c', 8);
/**
* 設置元素出隊模式
* SplPriorityQueue::EXTR_DATA 僅提取值
* SplPriorityQueue::EXTR_PRIORITY 僅提取優先級
* SplPriorityQueue::EXTR_BOTH 提取數組包含值和優先級
*/
$pq->setExtractFlags(PQtest::EXTR_BOTH);
//從頂部取出一個節點,該節點下面的節點移上為頂部節點;
print_r(
$pq->extract()
);
/*
[data] => b
[priority] => 1
*/
$pq->recoverFromCorruption();
//拿出頂部節點
print_r(
$pq->extract()
);
/*
[data] => c
[priority] => 8
*/
// 還原自上一個節點? 沒什么效果?
$pq->recoverFromCorruption();
print_r(
$pq->current()
);
$pq->rewind();
while($pq->valid()){
print_r($pq->current());
echo PHP_EOL;
$pq -> next();
}
```
- 現代化PHP特性
- php7常用特性整理
- 反射機制Reflection
- 依賴注入與服務容器
- 抽象類與接口
- 類多繼承的替代方案Traits
- 類的延遲綁定(后期綁定)
- 生成器語法
- 匿名函數和閉包
- 匿名類
- 理解php的output buffer
- 斷言ASSERT
- 魔術方法小結
- Zend Opcache字節碼緩存
- 內置的http服務器
- SPL標準庫
- 【SPL標準庫專題(1)】SPL簡介
- 【SPL標準庫專題(2)】Iterator
- 【SPL標準庫專題(3)】Classes
- 【SPL標準庫專題(4)】Exceptions
- 【SPL標準庫專題(5)】Datastructures:SplDoublyLinkedList
- 【SPL標準庫專題(6)】Datastructures:SplStack & SplQueue
- 【SPL標準庫專題(7)】Datastructures:SplPriorityQueue
- 【SPL標準庫專題(8)】Datastructures:SplHeap & SplMaxHeap & SplMinHeap
- 【SPL標準庫專題(9)】Datastructures:SplFixedArray
- 【SPL標準庫專題(10)】Datastructures:SplObjectStorage
- PHPcomposer使用手札[ing]
- PHP中的多態
- 通過命名空間實現自動加載的框架雛形
- 日期與金額
- PHPstorm使用攻略
- 筆記本