Lists And Vectors

Objects of a class can be stored into array-like collections. For List and Vector, unlike arrays, the elements count is not necessary to be specified.

Vector VS List

There are many differences between both of them. Most important them are:

List

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

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.

List

To use list we should add the following include:

If we want to iterate him via an iterator, we need to add this one too:

Syntax for defining list:

Here's an example:

Output:

Explanation:

  • In the for loop at lines 64 - 68 students object are created and added to school's list of student.
  • Using size() at line 71 the count of list elements is printed.
  • At lines 76 - 82 all list elements are looped and only the students older than 15 years old are printed.
  • At line 88 an iterator is created that points to the beginning of the list.
  • Line 89 moves the iterator 3 positions ahead. This way the element at the 3rd index (0 + 3) is reached

Vector

To use vector the following include has to be added:

Here's an example:

Output:

Explanation:

  • At lines 60 - 64 car objects are created and added to the vector.
  • At lines 72 - 78 all elements of the vector are looped. Cars with price lower than 25000 are printed.
  • At line 83 the car at index 3 is printed.