Lists

Introduction

List is a collection similar to array but without specific size.

There are couple of things to remember about it:

List

  • Element at random index cannot be accessed directly. To do it an iterator must be used.
  • It's suitable for large sets of data.
  • A size (elements count) cannot be defined.

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

Also if there is need of access to element at specific index, the following needs to be included:

Syntax

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

Initialization

Empty List

Initial Elements

Looping elements

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

Output:

Adding element to the back

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

Size

Size is the count of elements in collection.

In order to get it the size function is used.

Example:

Output:

Accessing specific index

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

Output:

There are couple of things to notice:

  • In order to access element at specific index the iterator library needs to be added (line 6).
  • The iterator starts from the 0-th index of collection - line 21.
  • Afterwards it's moved to the 3-rd index - line 22.
  • The iterator points to a specific element which is accessed at line 24.

Outside of bounds

Iterator which moves outside ot list bounds results in exception.

Let's look at the following:

The collection has 3 elements but the iterator moves 5 elements ahead. This causes an exception.