C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ STL

Vectors in C++ Standard Template Library (STL)

Learn: In this article, we are going to discuss about one of the most useful containers in the C++ STL known as vector. Through this article we’ll see some basics about vectors and their member functions with example.
Submitted by Abhishek Jain, on January 23, 2018

Vector is the most useful container in the STL. All the STL containers are useful, but you'll find yourself reaching for vector more often than other. Vectors are designed to replace most applications of arrays and arrays are so useful, they've been included in every commercially successful programming language.

Vectors serve you better than arrays when memory required is undefined at the time of dynamic memory allocation. Vectors are capable to increase its size at runtime (reallocation). It consumes extra space to efficiently store and increase its size dynamically.

Their memory grows as elements are added to these containers, and when a vector is destroyed, its destructor automatically destroys the elements in the container and de-allocates the memory holding those elements.

Syntax: vector<type>vector_name;

Example: vector<int>v;

Some useful member functions of vectors

  1. push_back(): This function add a new element at the end of vector after its current last element.
  2. pop_back(): This function removes the last element from the vector.
  3. begin(): It returns a iterator pointing to the first element of the vector.
  4. end(): It returns a iterator pointing to the last elements of the vector.
  5. size(): This function returns the size(number of elements) of the vector.
  6. clear(): It removes all the elements of the vector, making it empty with size 0.

C++ program to implement vectors using STL

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

int main()
{ 
	int i,k;
	//vector declaration
	vector<int>v;
	
	//printing size before insertion
	cout<<"Before Insertion:"<<v.size()<<endl;
	
	//input elements
	cout<<"Enter Elements:";
	for(int i=1;i<5;i++)
	{ 
		cin>>k;
		v.push_back(k);
	}
	
	cout<<"Size after Push_back():"<<v.size()<<endl;
	v.pop_back();
	
	cout<<"Size after Pop_back():"<<v.size()<<endl;
	cout<<"Elements Present in vector are:";
	for(vector<int>::iterator j=v.begin();j!=v.end();j++)
		cout<<*j<<" ";
	cout<<endl;
	
	//clearing vector
	v.clear();
	cout<<"After clear():"<<v.size()<<endl;
	
	return 0;
}

Output

Before Insertion:0
Enter Elements:4 86 23 1
Size after Push_back():4
Size after Pop_back():3
Elements Present in vector are:4 86 23
After clear():0


Liked this article? Do share with your friends :)


COMMENTS