Read this in other languages: English, Português
- What is a vector?
- Where are vectores used?
- How to implement a vector?
- What are the basic operations in a vector?
A vector is a linear data structure that efficiently supports random access to any of its elements. To do this, the elements of a vector must all have the same type and be stored contiguously in memory. Thus, an element can be uniquely indexed from its relative position in this data structure.
An analogy for vectors are staircases. Several steps of the same size are arranged contiguously and a step can be uniquely identified by its relative position to the first step of the staircase.
- To implement other data structures, such as Stacks and Queues.
A vector v can be constructed with the following components:
v.elements[]: an array that stores the elements of the vector.v.length: an integer that indicates the number of elements stored in the vector.v.capacity: an integer that indicates the maximum number of elements that can be stored in the vector.
- If the length of the vector
v.lengthis equal to its capacityv.capacity, expand the capacity of the vector. - Increment the length of the vector
v.lengthby one. - Shift all elements of the vector
vthat are to the right of the insertion indexione position to the right. - Store the element
xat positioniof the vectorv.
- If the removal index
iis greater than the length of the vectorv.length, return"invalid index". - Save in
xthe element stored at positioniof the vectorv. - Shift all elements of the vector
vthat are to the right of the removal indexione position to the left. - Decrement the length of the vector
v.lengthby one. - Return the element
x.