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.

header: Declaration: vector <data_type> v; static vector <data_type>* v = new vector(); //note the parentheses // We can specify initial capacity by providing an integer paremeter to the constructor. e.g vector pq(23); Remember that this inserts a garbage of type int, i.e size()==capacity(). Methods:

  1. vector_name.push_back(T) - append. We **must **use this function only, as it checks for capacity and updates size.
  2. vector_name.at(i) - access/modify value at index i, if within size. Can be used as lvalue too.
  3. 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.
  4. v.**size() **- returns the number of elements in the vector.
  5. v.**capacity() **- returns the capacity of the vector. i.e maxium elements which can be taken without resizing.

Learnt on my own:

  1. v.reserve(int i) - makes the initial capacity as the i places.
  2. **clear() - **makes size = 0. size() does not return an lvalue.
  3. v.**insert(position, value) **inserts the value at index position and returns the iterator to the place where it has inserted val.
  4. v.begin() - returns iterator to the first element
  5. v.end() - returns iterator to one place after the last element. i.e iterator to v.at(i+1). It may not exist though.
  6. = operator does a deep copy of the vector.
  7. To slice a vector, use the vector’s constructor(v.begin(), v.end())

Note: Just don’t try to break the abstraction. Advantages:

  1. Very space efficient. Least wastage.
  2. Fastest access.
  3. Doubling decreases the sporadic insertion time. Can be compensated with reserve().