# Vectors - Introduction

Vectors are similar to arrays as vectors also use contiguous storage locations for their elements.

But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

# Source Code - C++

#include <iostream>
#include <vector>
using namespace std;

// Function to Display Vector
void dispVector(vector<int> A)
{
 vector<int>::iterator it;

 for(it=A.begin();it!=A.end();it++)
  cout<<*it<<" ";
  cout<<"\n";
}
// Main Function
int main() {

 //Declaring a vector of size 4 and initialising to zero
 vector<int> A(4,0);
 int i;

 // Calling Display function
 dispVector(A);

 // Taking input in vector
 cout<<"Enter 4 elements\n";
 for(i=0;i<4;i++)
  cin>>A[i];

 dispVector(A);
 //adding 5 at the end of vector
 cout<<"Adding 5 at the end\n";
 A.push_back(5);
 dispVector(A);
 cout<<"Size:"<<A.size()<<"\n";

 //Deleting last element from the vector
 cout<<"Deleting last element\n";
 A.pop_back();
 dispVector(A);
 cout<<"Size:"<<A.size()<<"\n";

 //Inserting 8 at index 2
 cout<<"inserting 8 at index 2\n";
 A.insert(A.begin()+2,8);
 dispVector(A);

 //Deleting element at index 3
 cout<<"Deleting element at index 3\n";
 A.erase(A.begin()+3);
 dispVector(A);

 return 0;
}

Learn More


  • Vectors - Introduction