Vectors

#include "vector.tcc"

A Vector is a sequence container that implements storage of data elements. The type of the vector is given at initialisation time via a template parameter, e.g., int.

Vector<int> v;
Vector<int> u(12);

In this example, Vector v is of size 0 and u is of size 12. A Vector can also be initialised with a pointer to an allocated block of memory.

Vector<int> v(12, data);

The memory block is freed when the Vector is destroyed. If this is not desirable, an additional flag destroy can be passed to the constructor as follows.

Vector<int> v(12, data, false);

This behaviour can also be changed by manipulating the destroy member variable.

A Vector can be resized using the resize method.

v.resize(20);

The size member variable contains the current size of the Vector.

Element retrieval and assignment is done in the usual way.

int i = v[10];

v[11] = 9;

Note that a Vector, like any higher order data structure, should be passed by reference.

Class definition

template<class T>
class Vector

Generic Vector.

Public Functions

Vector(size_t const)

Create a Vector with size elements.

Parameters

sizeVector size.

template<size_t n>
Vector(T const (&)[n])

Create a Vector with size elements from a C array.

Parameters

arr – C array.

Vector(T*const, size_t const)

Create a Vector with size elements from a block of raw memory.

Parameters
  • ptr – Pointer to data, Vector takes ownership.

  • sizeVector size.

T *data() const

Get the underlying data.

Returns

data.

size_t size() const

Get the number of elements.

Returns

Vector size.

void resize(size_t const)

Set the number of elements.

Parameters

sizeVector size.

void clear()

Clear the contents.

void push_back(T const&)

Add an element to the back.

Parameters

el – Element.

void push_back(T const&&)

Add an element to the back.

Parameters

el – Element.

T pop_back()

Remove an element from the back.

Returns

Element.