Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Element to End of Vector

Tags:

scala

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?

like image 966
Kevin Meredith Avatar asked Sep 10 '13 16:09

Kevin Meredith


People also ask

How do you 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.

Can you add elements to front vector?

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 ...

How do you add elements to a vector array?

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.


1 Answers

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

like image 67
David Holbrook Avatar answered Nov 16 '22 02:11

David Holbrook