ruby 是否有一个列表类型可以在添加/删除发生时保持内容排序?

发布于 2024-08-18 22:00:51 字数 650 浏览 3 评论 0原文

我需要 Ruby 中的一个数据结构,在添加或删除元素时保持其元素排序,并允许(至少)能够从列表中弹出第一个元素。

我在 ruby​​ 文档中找到的最接近的东西是 SortedSet 。但是,这似乎没有提供任何通过索引访问元素的方法(甚至弹出第一个元素)

这些是我需要的特定操作:

  • 将对象添加到列表中 从
  • 列表中弹出第一个对象
  • 检查是否存在对象在列表中
  • 从列表中删除对象(按对象,而不是按索引)

ruby​​ 是否为此内置了任何东西,或者是否有任何我可以获取的库可以将其提供给我?我可以毫不费力地实现一个,但如果可能的话,我宁愿使用预先存在的一个。

目前我使用的是 Ruby 1.8,不过切换到 1.9 可能没问题。

编辑:

由于似乎存在一些混乱,我需要的排序不是对象插入的顺序。我需要基于 <=> 运算符进行排序。一般来说,我会弹出第一个元素,处理它(可能会生成新元素),将新元素添加到列表中,然后重复。添加的元素可能会出现在排序顺序中的任何位置,而不仅仅是末尾。

I need a datastructure in Ruby that keeps its elements sorted as elements are added or deleted and allows (at least) the ability to pop the first element off the list.

The closest thing I've found in the ruby docs is SortedSet. However, this doesn't seem to provide any way to access the elements by their index (or even pop the first element off)

These are the specific operations I need:

  • Add object to the list
  • Pop first object off of the list
  • Check if an object is in the list
  • Remove object from the list (by object, not by index)

Does ruby have anything built in for this, or are there any libraries I can grab that would give it to me? I could implement one without too much difficulty but I'd rather use a preexisting one if possible.

Currently I'm using Ruby 1.8, though switching to 1.9 would probably be ok.

EDIT:

Since there seems to be some confusion, the sorting I need isn't the order that the objects are inserted. I need the sorting to be based on the <=> operator. Generally I'll be popping the first element, processing that (which may generate new elements), adding new elements to the list, then repeating. The elements being added could end up anywhere in the sorting order, not just at the end.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀お生予夺 2024-08-25 22:00:51

可能需要考虑这个与 1.8 兼容的红黑树 gem,它可以做到这一点(Ruby/RBTree):

http://www.geocities.co.jp/SiliconValley-PaloAlto/3388/rbtree/README.html

树总是保持平衡,树上的操作是 O(log N )

这里还有一个红黑树实现:

http://github.com/kanwei/algorithms

::RubyRBTreeMap

may want to condiser this 1.8-compatible gem for red black trees which does this (Ruby/RBTree):

http://www.geocities.co.jp/SiliconValley-PaloAlto/3388/rbtree/README.html

tree is always kept balanced, operations on the tree are O(log N)

there's also a red black tree implementation here:

http://github.com/kanwei/algorithms

Containers::RubyRBTreeMap

暮色兮凉城 2024-08-25 22:00:51

尽管效率较低(如果您经常使用它),SortedSet 有一个 to_a 方法,您可以使用它来访问项目:

s = SortedSet.new
s << 1
s << 0
s << 3
puts s.to_a[0] # => 0

Although inefficient (if you use it often), SortedSet has a to_a method that you can use to access the items:

s = SortedSet.new
s << 1
s << 0
s << 3
puts s.to_a[0] # => 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文