Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are vectors and how are they used in programming?

I'm familiar with the mathematical/physics concept of a vector as a magnitude and a direction, but I also keep coming across references to vectors in the context of programming (for example C++ seems to have a stl::vector library which comes up fairly frequently on SO).

My intuition from the context has been that they're a fairly primitive construct most often used to represent something along the lines of a variable length array (storing its size as the magnitude, I presume), but it would be really helpful if somebody could provide me with a more complete explanation, preferably including how and why they're used in practice.

like image 726
Lawrence Johnston Avatar asked Feb 03 '09 18:02

Lawrence Johnston


People also ask

How are vectors used in programming?

Vectors are used in many programming languages as data structure containers. They have a dynamic structure and provide programmers with the ability to allocate container size and memory space quickly. In this sense, vectors can be thought of as dynamic arrays.

What is a vector in computer?

Vector graphics are computer images created using a sequence of commands or mathematical statements that place lines and shapes in a two-dimensional or three-dimensional space. In vector graphics, a graphic artist's work, or file, is created and saved as a sequence of vector statements.

What is vector based programming?

A vector graphics editor is a computer program that allows users to compose and edit vector graphics images interactively on a computer and save them in one of many popular vector graphics formats, such as EPS, PDF, WMF, SVG, or VML.


1 Answers

From http://www.cplusplus.com/reference/stl/vector/

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.

Furthermore, vectors can typically hold any object - so you can make a class to hold information about vehicles, and then store the fleet in a vector.

Nice things about vectors, aside from resizing, is that they still allow access in constant time to individual elements via index, just like an array.

The tradeoff for resizing, is that when you hit the current capacity it has to reallocate, and sometimes copy to, more memory. However most capacity increasing algorithms double the capacity each time you hit the barrier, so you never hit it more than log2(heap available) which turns out to be perhaps a dozen times in the worst case throughout program operation.

-Adam

like image 175
Adam Davis Avatar answered Oct 24 '22 17:10

Adam Davis