Vectors
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.
Vector Example
Iterators
begin() – Returns an iterator pointing to the first element in the vector
end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector
rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
cbegin() – Returns a constant iterator pointing to the first element in the vector.
cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
Capacity
size() – Returns the number of elements in the vector.
max_size() – Returns the maximum number of elements that the vector can hold.
capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.
resize() – Resizes the container so that it contains ‘g’ elements.
empty() – Returns whether the container is empty.
shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
reserve() – Requests that the vector capacity be at least enough to contain n elements.
Element Access
reference operator [g] – Returns a reference to the element at position ‘g’ in the vector
at(g) – Returns a reference to the element at position ‘g’ in the vector
front() – Returns a reference to the first element in the vector
back() – Returns a reference to the last element in the vector
data() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
Modifiers
assign() – It assigns new value to the vector elements by replacing old ones
push_back() – It push the elements into a vector from the back
pop_back() – It is used to pop or remove elements from a vector from the back.
insert() – It inserts new elements before the element at the specified position
erase() – It is used to remove elements from a container from the specified position or range.
swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.
clear() – It is used to remove all the elements of the vector container
emplace() – It extends the container by inserting new element at position
emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
How do vectors in C++ work?
Typically, vectors have to be declared first in any program which uses them. The usual syntax is as follows:
The optional element in the syntax is the <no. of elements> portion, which can either be declared or not. The syntax would then be:
The above is an example of an empty vector which will have zero elements in it. To break down the syntax of a vector, the argument <type> is the data type that one would like to store in the vector. These can be an integer, double or string type depending on the value stored. The ‘variable name’ can be anything that the programmer chooses it to be. Some examples of vector code are as follows:
The above command line in C++ would create a vector with the name ‘age’, ‘grades’ and ‘names’. The type of value that the vector ‘age’ is allowed to store will be whole integers only, i.e. numbers without decimal places. Similarly, ‘grades’ will be able to store decimal values and ‘names’ will store in the form of strings. The size of the vector is specified by the number 20, i.e. it will allow for the storage of 20 values under the same variable ‘age’. So this is a classic example of declaring vectors in the programming language C++.
Individual elements in the vector can be referred with the use of square brackets after the vector has been declared in the following fashion:
However, simply declaring a vector in the program would not work until a directive called #include is provided in the beginning of the program. This is because since vectors are a Standard Library facility, and not a built-in part of the core language. The example is as follows:
The above code would activate the vector and make it usable in the program. These were the basics of activating, declaring and referring to individual elements in a vector. A typical program which will allow the entry of student grades will look like the following:
Dynamic nature of vectors
As discussed earlier, that vectors are special given that they can be dynamic in nature i.e. they can be resized. Vectors can be resized during the program execution to include or even reduced in size.
In the example from the previous fragment above, if we don’t know ahead of time (i.e., at the time we are writing the program) that there are 20 students, we could obtain that information at run-time (e.g., prompt the user for the number of students) and resize the vector accordingly, as shown below (though we notice that the example is somewhat silly, in that we could have waited until having the value of num_students and then declare the vector initializing it with that size):
Notice that the valid subscripts for a vector with num_students elements are 0 to num_students−1. For that reason, the for loop starts at 0 and goes while i is less than num_elements.
Inserting and Removing Elements
Methods push_back and pop_back insert and remove (respectively) elements at the end of the vector. For situations where we need to insert or remove at an arbitrary position, we have methods remove and remove. We notice that these methods are inefficient with a vector (they take linear time` since all the remaining elements from the given position to the end have to be shifted). However, for situations where we must support these operations, class vector does provide the facilities to do so.
Methods insert and remove use iterators (discussed in the next section) as parameters to indicate the position at which we want to insert or remove the element(s). However, a “quick and dirty” solution is available, given the nature of vector iterators (they support operations essentially identical to pointer arithmetic). The code sample below illustrates these features:
In the sample above, the expressions values.begin() + n work similarly to the idea of getting a pointer to element n of an array – we get a pointer to the first element of the array, then add an integer offset to obtain a pointer pointing n elements after the beginning of the array. The expression values.begin() returns an iterator pointing to the first element of the vector, and adding an integer value n results in an iterator pointing n positions after the first element, providing the required parameter for insert and remove methods.
All Vector Functions
Last updated