Q:

Vectors in C++ Standard Template Library (STL)

belongs to collection: C++ programs on various topics

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to Find Nth element of the X-OR sequen... >>
<< C++ program to find the integers which come odd nu...