scala 将元素添加到向量的末尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18724219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:39:03  来源:igfitidea点击:

Adding Element to End of Vector

scala

提问by Kevin Meredith

Scaladocsexplain how to add an element to a Vector.

Scaladocs解释了如何向 Vector 添加一个元素。

def :+(elem: A): Vector[A]
[use case] A copy of this vector with an element appended.

Example:

例子:

scala> Vector(1,2) :+ 3
res12: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)

For a large collection, it seems expensive to copy the whole Vector, and then add an element to it.

对于大型集合,复制整个 Vector,然后向其中添加元素似乎很昂贵。

What's the best(fastest) way to add an element to a Vector?

将元素添加到 Vector 的最佳(最快)方法是什么?

采纳答案by David Holbrook

Concatenation to an immutable Vector is O(logN). Take a look at this paper to see how it is done.

连接到一个不可变的 Vector 是 O(logN)。看看这篇论文,看看它是如何完成的。

http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf

http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf

回答by coltfred

If you're going to be doing a lot of appends you should use a Queue as it guarantees constant time append. For information on the time complexity of collections you can refer to this cheat sheet.

如果您要进行大量追加,则应使用队列,因为它可以保证恒定时间追加。有关集合时间复杂度的信息,您可以参考此备忘单。

http://www.scala-lang.org/docu/files/collections-api/collections_40.html

http://www.scala-lang.org/docu/files/collections-api/collections_40.html

回答by ski629

Appending to a vector in Scala takes effectively constant time. The vector is copied in the sense that many of its data structures are reused, not in the sense that all of the elements are copied into a new vector. See the link provided by coltfred for more information about time complexity of collections:

附加到 Scala 中的向量需要有效的恒定时间。向量被复制的意义在于它的许多数据结构被重用,而不是所有元素都被复制到一个新的向量中。有关集合时间复杂度的更多信息,请参阅 coltfred 提供的链接:

http://www.scala-lang.org/docu/files/collections-api/collections_40.html

http://www.scala-lang.org/docu/files/collections-api/collections_40.html