Scaladocs explain how to add an element to a 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.
What's the best(fastest) way to add an element to a Vector?
To add elements to vector, you can use push_back() function. push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.
Keep in mind that pushing stuff to the front of the vector is an O(n) operation, so if you need to do it repeatedly you probably want to use a data structure better optimized for that (such as std::deque ), or use other tricks (e.g. if you only add and remove stuff at the front, just do that at the end and display it ...
vector insert() function in C++ STL std::vector::insert() is a built-in function in C++ STL which inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
Concatenation to an immutable Vector is O(logN). Take a look at this paper to see how it is done.
http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With