97
STL - Vector
Vector
C++ STL

Vector is one of various useful containers defined under Standard Template Library(STL). We can say that Vector is an advanced version of array in C++ . Though it contains some good features than array.

Vector Header File ,

#include<vector>

Vector Declaration , Syntax : `

vector<data_type> identifier (size, initial_value) ;     // Here size & initial_value are optional

Example :

vector<int> A (5,-1) ;  // vector of size =5 with all elements in vector initialised with value =  -1

Insertion in Vector , There are two ways for inserting an element in a Vector , either you can use push_back() or insert(index,value) , insert() will insert value at index give , and push_back() will insert value after the last element which is already in vector. And insert() will insert the value as well as it will swap all the preceding elements by the number of elements inserted

Example :

  A.push_back(5) ;           // A = {-1 ,-1, -1, -1, -1 , 5 }    , vector can expand its size

  A.insert(1,6) ;                 // A = {-1, 6 , -1 ,-1 , -1, -1 , 5}

Resizing the vector :

A.resize(10) ;              // now the vector 'A' has size = 10

Erase all the values of vector :

A.erase() ;//Erase all values of vector A

Erase values of vector lie in a given interval :

A.erase(1,5) ;  // Erase values from index = 1 to 5

Check if any vector is empty :

 if ( A.empty() ) { //Statements  }

Importing value of any array into a vector , let an array array like

 int array[ ] = {1,2,3,4,5} ;

vector<int> A (array , array + 5)  ;   // It will make vector elements  A =  {1,2,3,4,5}

Size of vector :

int size = A.size() ; // it gives size of vector 'A' , i.e. number of elements present in vector 'A'

Creating Matrix with help of Vector ,

vector<int, vector<int> > Mat (M , vector<int> N) ;  // Matrix of size  M*N

Many <algorithm> library function can be implemented on vector(s) , that I will explain in <algorithm> Note

Author

Notifications

?