Skip to main content

Section 13.1 What are vectors?

A vector is an ordered sequence of values stored in one contiguous block; the values in the vector are called elements and are identified by indexes starting from 0. The elements can be of any type (but in C++ all the elements of a vector must be the same type). Thus we can have a vector of integers or a vector of strings:
Figure 13.1.1. A vector of ints.
Figure 13.1.2. A vector of strings.
An ordered collection is often referred to as a list and is one of the most common types of container for holding multiple pieces of data. An ordered collection that stores its data in one large block is known as an array. So another way to describe a vector is as an β€œarray based list”. Most programming languages have an equivalent container, but the name tends to vary. In Python the most similar structure is a list; in Java it is an ArrayList; in JavaScript it is an array
In C++ there are also a separate type array. Arrays in C++ are a more primitive structure - they are literally just a large block of memory that contains a sequence of smaller items. Vectors on the other hand are objects (in the same way strings are). A vector contains both data (an array) and functions that make it easier to work with that data.
You will notice many similarities between vectors and strings. This is not a coincidence - the two types are designed to do similar jobs. They both hold an ordered sequence of items. And it is perfectly legal to make a vector that holds chars. The primary difference is that when using a string, it is assumed that the value of the entire sequence has some meaningβ€”the string "Hello world", represents a piece of text. A vector of chars would just represent a list of individual characters (’h’, ’e’, ’l’...).
You have attempted of activities on this page.