CSE 202: Computer Science II, Winter 2018
std::vector

While std::string stores a resizeable character array, std::vector stores a resizeable array of any type.

std::vector is not a type or class. It is a class template which you will learn more about towards the end of the course. std::vector represents a family of types for the storage and manipulation of a dynamic array. It is found in the <vector> header file. To generate a type from std::vector, std::vector must be instantiated by supplying a type to it's template parameter.

The declaration std::vector<double> v; creates a variable of type std::vector<double>.

Here are some operations supported by a vector for some variable v whose elements are for some type T:

Expression Meaning
v = v2 Copies all the elements from vector v2 and assigns them to v
v[i] Accesses the element of v at index i
v.front() Accesses the first element of v
v.back() Accesses the last element of v
v.empty() Returns true if v has zero elements
v.size() Returns the number of elements in v
v.clear Deletes all elements from v
v.push_back(x) Appends an element with value x to v
v.pop_back() Deletes the last element from v

A vector also supports insert and erase like std::string does, but it requires the use of iterators which you will learn about soon.

A vector cannot be initialized from an initializer list unless your compiler is using C++11 or higher.