Vectors
- This is chapter 18, the beginning
- reference.
- This is your new favorite C++ array. Use it unless forbidden.
- He provides a list of requirements to use these containers on 629-630
- These are things you should implement in your classes anyway.
- We will discuss these in detail in chapter 7-10
- The vector class implements a dynamic array.
- Sequential container
- Grows and shrinks as needed.
- Constant time random access - what does that mean?
- Plus access to the underlying storage if needed
- For libraries from C for example.
- Not for normal access.
- constant insert/delete at the end.
- O(n) insert/delete anywhere else - but as measured from the end.
-
#include <vector>
- Declaration and initialization
- It is a template so we need to specify the type.
-
vector <type> identifier
-
vector <int> values;
-
vector <BeetleT> bugs;
- A using statement is sometime helpful here
-
using BugArrayT = vector < BeetleT>;
- There are several ways to initialize a vector
-
vector<type>id
build an empty vector.
-
vector<type>id(size_t,[{values}])
builds a vector of size initializing to the given values.
- There are others. The cppreference page has 10 different versions.
- Declaring a multi dimensional vector
- The member functions to know:
- push_back, pop_back: add or remove the last element.
- size() or length() : return the number of elements.
- [i] or .at(i) : access element i, 0 ≤ i < size()
- front(), back(): access the first/last element.
- True assignment (=)
- data(): returns a pointer the the underlying storage, for use with c routines.
- see vecTest.cpp