Vector Slicing

Vector slicing allows you to extract a portion of a vector.

It takes two parameters: the start and end position. It returns a new vector containing the extracted portion.

Both start and end position can be specified via iterators using the begin and end functions.

Subvector Between Specified iterators

For example this slicing takes all of the list elements:

Output:

Selecting the first couple of elements:

Output:

In this example the first argument (animals.begin()) specifies that the subvector will start from the first element of the animals vector - "cat"

The second argument animals.begin() + 3 specifies that the end of the sliced vector should correspond to the 3rd element of the vector animals.

Selecting the last couple of elements:

Output:

In this case the first argument (animals.end() - 4) specifies that the sliced vector will start at the 4th element of the vector animals couting from the end to beginning.

The second argument animals.end() specifies that the end of the sliced vector should correspond to the end of the animals vector.

Removing Sublist

A sublist inside a List can be removed.

Output:

colors.erase(colors.begin() + 2, colors.end() - 1); selects the following sublist - "blue", "pink", "gray", "purple"

The erase function removes the elements of the sublist.

After removing the sublist elements, the remaining elements are - "white", "green", "red".

Invalid cases

Invalid cases result in an error. Such cases involve accessing elements outside of the vector bounds.

Example:

In this example, animals.end() + 1 is outside of the vector bounds which results in exception.

Another case for going outside of vector's range is:

In this case animals.begin() + 9 goes outside of the vector's bounds which results in exception.