Vectors

Introduction

Vector is a collection similar to array but with no need to specify size.

There are couple of things to remember about it:

Vector

  • Element at random index can easily be accessed.
  • It's suitable for small sets of data.
  • A size can be defined but it's not mandatory to specify it.

In order to use it the following line should be added:

Syntax

type specifies the values type - int, double, string, char etc...

Initialization

Empty Vector

Initial Elements

Fixed size

5 elements all of which have value of 0. If strings were hold the value of the elements would be empty string - "".

Set Default Value

Creates 3 elements all of which have value of 5.

Adding element to the back

This can be done via the push_back function. Like in the following code:

Accessing specific index

Accessing element at specific index is identical to arrays.

Let's add elements to vector and access the element at index 1.

Output:

Outside of bounds

Accessing element outside of vector's bounds results in exception.

Let's look at the following example

numbers has 3 elements (indexes from 0 to 2) but at line 10 the 3rd index is accessed.

Size

Size is the count of elements in collection.

In order to get it the size function is used.

Example:

Output:

Looping elements

Let's have a vector of ages and print only those who are greater than 20.

Output: