简体   繁体   English

go go go中可重用的优先级队列实现

[英]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. 对于Go没有泛型,它是目前唯一可用的选项。

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. 你需要你的heapable类型是一个结构,在你用于排序的字段上有一个像'pq:“Key”的标签,那个字段类型是<可比的。 It's far less powerful than a Less method but it might meet your needs. 它远不如Less方法强大,但它可能满足您的需求。

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. 我只是按照本书的说法,为每种类型分别实现heap.Interface。 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. 过去,标准库的container/vector模块中的向量类型基于可调整大小的片实现了这些方法,并且完美地用作与heap模块一起使用的容器。 Unfortunately, they got rid of vector , which I never understood as it implemented a nice method-level abstraction over a slice variable. 不幸的是,他们摆脱了vector ,我从未理解它,因为它在切片变量上实现了一个很好的方法级抽象。 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. 所以现在,每当我看到有人在Go中使用堆模块时,他们必须基本上重新实现vector一部分 - 基于切片变量编写PushPopLength等。

I'm not sure I understand the question. 我不确定我理解这个问题。

I've implemented a queue (and stack and ring) using interface{} as the stored type here: 我在这里使用interface {}作为存储类型实现了一个队列(和堆栈和环):

https://github.com/iNamik/go_container 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. 使用interface {}可以存储您想要的任何类型 - 虽然它无法帮助您强制执行类型,但它可以完成工作。

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. 如果您认为它有用,我很乐意添加一个优先级队列容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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