Pract 3
Pract 3
vectors
an example of a class: extends the idea of an array
declaration format:
vector<type> name;
vector<type> name[size];
vector<type> name[size] = {a,b,c};
default size 0, size doubles if insufficient
allows insertion / deletion, keeps track of size, and provides us with some
additional features
vec[0] is vec.at(0) is arr[0]
instead of having to worry about segfaults when accessing out of
bounds, the function will give an explicit out of bounds error:
easier to debug
instead of having to remember the position of the last element, we can
just vec.push_back(element)
instead of having to separately record the size, vec.size()
instead of having to write deletion/insertion algorithms, we use
vec.erase(vec.begin() + pos) and vec.insert(vec.begin() + pos,
el)
however, this also changes the size, which may cause problems
with iteration
the vec.begin() is required because of how vectors work
internally, it's analagous to position 0
passing vectors
unlike arrays, vectors are passed by value: if you want a function to
modify a vector and get the modified vector back, you have to either
return the vector or pass it by reference.