1. Vector aka Dynamic Array #
Created Friday 24 January 2020
Vector is just another name of our Dynamic Array. Exactly the same as our implementation.
- It has been implemented in STL.
- Doubles the size when the size is less.
- Keeps a size variable.
- Keeps a capacity variable.
- Starts from size 0, i.e NULL.
- Can be used dynamically and statically.
header:
- vector_name.push_back(T) - append. We **must **use this function only, as it checks for capacity and updates size.
- vector_name.at(i) - access/modify value at index i, if within size. Can be used as lvalue too.
- v[i] can also be used, but it is not safer for insertion, as it does no range checking. Use it only when you are sure of the index.
- v.**size() **- returns the number of elements in the vector.
- v.**capacity() **- returns the capacity of the vector. i.e maxium elements which can be taken without resizing.
Learnt on my own:
- v.reserve(int i) - makes the initial capacity as the i places.
- **clear() - **makes size = 0. size() does not return an lvalue.
- v.**insert(position, value) **inserts the value at index position and returns the iterator to the place where it has inserted val.
- v.begin() - returns iterator to the first element
- v.end() - returns iterator to one place after the last element. i.e iterator to v.at(i+1). It may not exist though.
- = operator does a deep copy of the vector.
- To slice a vector, use the vector’s constructor(v.begin(), v.end())
Note: Just don’t try to break the abstraction. Advantages:
- Very space efficient. Least wastage.
- Fastest access.
- Doubling decreases the sporadic insertion time. Can be compensated with reserve().