Skip to content

SpecificationIII · Types and values

3.5

Vectors

A vector is a list that grows and shrinks while the program runs; all its elements have the same type.

Markdown version

3.5.1 How to write it

Define «name» As vector<«type»> <- vector();
«name».append(«value»);
«name».insert(«position», «value»);
«name».remove(«position»);
«name»[«position»]

3.5.2 How it works

Unlike an array, a vector has no fixed size. It starts empty and grows with append (at the end) or insert (at a position); it shrinks with remove. Positions count from zero and length says how many elements it has.

ProgramThe shopping list

Algorithm Compra
  Define lista As Vector<String> <- vector();
  lista.append("pan");
  lista.append("leche");
  lista.insert(0, "fruta");
  Write lista, " ", lista.length();
  lista.remove(1);
  lista.sort();
  Write lista, " ", lista.contains("pan");
EndAlgorithm

Output

["fruta", "pan", "leche"] 3
["fruta", "leche"] false

The program finishes normally.

  1. 1The vector starts empty.

  2. 2append puts "pan" at the end and then "leche".

  3. 3insert(0, …) puts "fruta" at the start and shifts the rest.

  4. 4remove(1) takes out position 1 and the rest moves left.

Figure 3.5-1.A vector grows and shrinks. Inserting shifts what was already there to the right; removing closes the gap.

A dashed box representing the vector lista, with positions numbered 0, 1 and 2. Stepping forward, pan and leche appear; then fruta at the start, shifting the others; finally pan disappears and leche moves to position 1.

3.5.3 A shared reference

A vector is a reference: two variables can point to the same vector. If it is changed through one of them, the other sees the change, because there are not two vectors but one.

ProgramTwo names, a single vector

Algorithm Compartido
  Define a As Vector<Integer> <- vector();
  Define b As Vector<Integer> <- a;
  b.append(5);
  Write a.length(), " ", a;
EndAlgorithm

Output

1 [5]

The program finishes normally.

To get an independent copy, use copy.

3.5.4 Methods

MethodWhat it does
append(x)Adds at the end
insert(i, x)Adds at position i (from 0 to the length)
remove(i)Takes out position i
length()How many elements there are
sort()Sorts from smallest to largest; accepts a comparator
reverse()Turns the order around
contains(x)True if x is there
indexOf(x)Some(position) or None

In short

  • A vector grows and shrinks; all its elements have the same type.
  • Positions from zero; going outside is a failure.
  • It is a reference: assigning it shares the same vector.
  • copy creates an independent one.