简体   繁体   中英

Reusable Priority queue implementation in google go

如何在Google Go中编写可重用优先级队列的代码,或者每当需要优先级队列实现时,是否可以定义Less PushPop函数?

The later case is what one has to do. As far as Go doesn't have generics, it's the only available option at the moment.

Haven't tried it, but maybe you could use reflection and struct tags, if your cases happened to fit certain restrictons. You would require that your heapable type be a struct with a tag like `pq:"Key"` on the field you use for ordering, and that that field type be < comparable. It's far less powerful than a Less method but it might meet your needs.

Sorry I have no example code for you. I don't think it wouldn be terribly hard, but it would take me some time. Left for an exercise.

I might try this technique if I had a situation where I needed to handle arbitrary structs and I could live with the simplistic key restriction. For a finite set of types though, I wouldn't do this. I would just do it by the book, implementing heap.Interface separately for each type. It's really not that much work nor that many lines of code.

There used to be vector types in the container/vector module of the standard library that implemented these methods, based on a resizable slice, and perfectly worked as the container to be used with the heap module. Unfortunately, they got rid of vector , which I never understood as it implemented a nice method-level abstraction over a slice variable. So now, every time I see someone using the heap module in Go, they have to basically re-implement part of vector -- writing Push , Pop , Length , etc. based on a slice variable.

I'm not sure I understand the question.

I've implemented a queue (and stack and ring) using interface{} as the stored type here:

https://github.com/iNamik/go_container

Using interface{} allows you to store any type you want - although it doesn't help you enforce types ala generics, it gets the job done.

I could see creating a priority queue without much hassle.

Am I missing something?

I'd be happy to add a priority queue container if you think you'd find it useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM