github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/container/heap/example_pq_test.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This example demonstrates a priority queue built using the heap interface. 6 package heap_test 7 8 import ( 9 "github.com/shogo82148/std/container/heap" 10 "github.com/shogo82148/std/fmt" 11 ) 12 13 // This example creates a PriorityQueue with some items, adds and manipulates an item, 14 // and then removes the items in priority order. 15 func Example_priorityQueue() { 16 // Some items and their priorities. 17 items := map[string]int{ 18 "banana": 3, "apple": 2, "pear": 4, 19 } 20 21 // Create a priority queue, put the items in it, and 22 // establish the priority queue (heap) invariants. 23 pq := make(PriorityQueue, len(items)) 24 i := 0 25 for value, priority := range items { 26 pq[i] = &Item{ 27 value: value, 28 priority: priority, 29 index: i, 30 } 31 i++ 32 } 33 heap.Init(&pq) 34 35 // Insert a new item and then modify its priority. 36 item := &Item{ 37 value: "orange", 38 priority: 1, 39 } 40 heap.Push(&pq, item) 41 pq.update(item, item.value, 5) 42 43 // Take the items out; they arrive in decreasing priority order. 44 for pq.Len() > 0 { 45 item := heap.Pop(&pq).(*Item) 46 fmt.Printf("%.2d:%s ", item.priority, item.value) 47 } 48 // Output: 49 // 05:orange 04:pear 03:banana 02:apple 50 }