Vectors are sequence container class that stores its elements in contiguous memory locations and implements dynamic array, which means it allocates memory at run time and resizes itself automatically when an element is inserted or deleted. Vectors can simply be thought of as an array that has the ability to automatically resize itself.

We need to import the header <vector> to make use of vectors.#include <vector>

VECTOR DECLARATION AND INITIALISATION

The syntax to declare the array is given below :

std::vector <data_type> vector_name; 

Example

#include <iostream>
#include <vector>
using namespace std;
int main()
{
 // Declaring a vector v 
 // having 0 elements
 vector <int> v;       
 // Declaring a vector v1
 // and assigning values.             
 vector <int> v1 = {1,2,3,4,5}         
 return 0;
}

COPYING A VECTOR

Method 1:

v2 = v1;                            // vector v2 is the copy of vector v1.

Method 2:

std::vector<int> v3;               // Declaring vector v3
auto v3(v1)                        // copying vector v1 to v3.

ACCESSING DATA

std::vector has the following functions to access the underlying data.

  1. front(): To access the first element of the vector.
  2. back(): To access the last element of the vector.
  3. at(): To access specific elements. (It provides bound check: If the element you are trying to access is out-of-bounds, at() throws an exception.)
  4. []: To access specific elements.( without bound check: [] operator will not provide any bounds checking, providing for faster access while increasing the risk of a segmentation fault.)
v1.front()     // for accessing first element of vector
v1.back()      // for accessing last element of vector
v1[0]          // for accessing element at oth index.
v1.at(4)       // for accessing element at 4th index.
  1. data() : The function returns a pointer to the first element which is used internally by the vector.
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // initialising vector
    vector <int> v = { 1, 2, 3, 4, 5 };
 
    // memory pointer pointing to the
    // first element
    int* pos = v.data();
 
    // prints the vector
    for (int i = 0; i < v.size(); i++)
        cout << *pos++ << " ";
 
    return 0;
}

ADDING AND REMOVING ELEMENTS

std::vector has a variety of functions to add or remove elements from the vector.

  1. push_back(): The function adds an element at the end of the vector and increases the size by 1.
  2. emplace_back(): emplace_back() allows for constructor arguments to be forwarded so that the new element can be constructed in place.
  3. pop_back(): The function deletes the last element present in the vector and reduces the size by 1.
  4. insert(): To insert elements at specific element. Supply an iterator to the location where the new element should be inserted:
  5. erase(): To erase a specific element, call the erase() function and supply an iterator to the element you want to remove.
int x = 0;
v2.push_back(x);                   // adds element to end
v2.pop_back(x);                    // deletes last element
v2.insert(v2.begin(),x);           // adds element in beg(v2.begin()).
v2.emplace_back(10);               // constructs an element in place at the end
v2.erase(v2.begin());              // wil erase the first element

MANAGING MEMORY

Extra memory can be allocated to prevent a std::vector to reallocate memory every time a new element is inserted. Additionally, if you remove elements from the std::vector, that memory remains allocated to the std::vector.

Luckily, the std::vector class provides us a few functions for managing memory.

  1. reserve(): Often, you are aware of how many elements you need to store in your std::vector (at least as a maximum). As reallocations are costly in terms of performance, you can use the reserve() function to make a single large allocation, reducing the runtime hit that may occur from frequent reallocations. NOTE: reserve() can only increase the vector size. If the requested capacity is smaller than the current capacity, nothing happens.
  2. shrink_to_fit() : shrink_to_fit() performs a memory allocation to achieve the reduced size. If you have reserved space greater than your current needs, you can shrink the buffer.
  3. clear(): The clear() function erases all elements in the vector without reducing the capacity.
  4. resize(): function to manually increase or decrease the size of your std::vector at will. If you are increasing the size using resize(), the new elements will be 0-initialized by default. You can also supply an initialization value for the new elements. If you are resizing to a smaller size, the elements at the end of the list will be removed.
v2.reserve(10)         // increase vector capacity to 10 elements
v2.shrink_to_fit();    // shrinks the buffer.
v2.clear()             // erases all elements 
v2.resize(5);          // resize to 5. The new elements will be 0-initialized
v2.resize(10, -1);     // resize to 10. New elements initialized with -1
v2.resize(4);          // shrink and strip off extra elements

NOTE: If you want to add space but don’t want to add elements to the vector, use the reserve() function instead of resize().

OTHER USEFUL INTERFACES

  1. size() : returns number of elements present.
  2. capacity(): returns the current amount of memory allocated for the vector in terms of the number of elements.

NOTE: size() returns the number of present elements, capacity() is the current upper limit on the number of memory blocks allocated.You can clear all elements in a std::vector by using the clear() function. This will set the size() to 0, but note that capacity() will remain at the previous allocation level.

  1. empty(): To check whether the vector is empty. 0-> true false otherwise.
  2. max_size(): This returns maximum size of a std::vector on the system.

FOR LOOP

 // Method 1
 for(int j = 0; j < v2.size(); j++)

 // Method 2
 for(auto &t: v2)

Example:

std::cout << std::endl << "v2: " << std::endl;
for (const auto & t : v2)
{
    std::cout << t << " ";
}
std::cout << std::endl;

SORT OPERATION

std::sort(v2.begin(), v2.end());

TIME COMPLEXITY

  1. Random access – O(1)
  2. Insertion or removal of elements at the end – O(1)
  3. Insertion or removal of elements – O(n)