AppDividend
Latest Code Tutorials

C++ Vector Tutorial With Example | Vector in C++ STL

0

C++ Vector Tutorial With Example | Vector in C++ STL is today’s topic. C++ Vector is a template class that is a perfect replacement for the right old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the C++ programmer from taking care of the allocated memory and help to operate consistently on the contained objects.

C++ Vector is a sequence of container that can be changed dynamically. Means you can change its size any time you want. Like an array, it also takes contiguous memory location, but the difference is Vector is dynamic where Array is not. So, let’s start the C++ Vector Tutorial With Example From Scratch.

Content Overview

C++ STL

The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

C++ Vector Tutorial With Example

The first step using a vector is to include the appropriate header.

#include <vector>

Note that the header file name does not have any extension; this is true for all of the Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace std. This means that you have to resolve the names by prepending std:: to them.

Header File

Before using a vector, you have to include the header file vector. See the below code.

#include<iostream>
#include<vector>
int main()
{
	return 0;
}

For small projects, you can bring the entire namespace std into scope by inserting a using directive on top of your cpp file.

Syntax of declaring Vector in C++

See the following syntax.

vector<object_type>vector_name;

See the following example.

#include<iostream>
#include<vector>
int main()
{
   vector<int> v;
   return 0;
}

vector::assign()

An assign() modifier is used to assign the content to the vector.

The vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

Syntax

vector.assign(int size, int value)
  1. size:  The number of values to be assigned value.
  2. value:  To be assigned to the vector name.

vector::push_back()

It pushes the elements into a vector from the back. It adds an element at the end of the vector. The new value is inserted into the vector at the end after the current last element, and the vector container size is increased by 1.

Syntax

vector.push_back(value)

The value parameter is required, and it is the value that needs to be added.

vector::pop_back()

It will delete the last element from a c++ vector. The pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

Syntax

vector.pop_back()

vector::insert()

It inserts new elements before the element at the specified position. It inserts the elements into the vector.

Syntax

vector.insert (position, value)
  1. position: It specifies the iterator which points to the position where the insertion is to be done.
  2. value: It specifies the value to be inserted.

vector::erase()

It erases the element from the vector. The erase() function is used to remove the element from specified positions. Elements are removed from the specified position of the container.

Syntax

vector.erase(startpos, endpos)

It has either startpos or endpos parameters or only startpos parameter. 

vector::swap()

It swaps the content in vector. This function is used to swap the contents of one vector with another vector of the same type and size.

Syntax

vector1.swap(vector2)

Vector2 is the parameter with which the content has been swapped.

vector::clear()

It clears the vector. The clear() function is used to remove or delete all the elements of the vector container, thus making it size 0.

Syntax

vector.clear()

vector::emplace()

The vector::emplace() is the STL in C++ which extends container by inserting the new element at the position. Reallocation happens only if there is the need for more space. Here the container size increases by one. It constructs and inserts the element in the vector.

Syntax

template <class... Args>
iterator emplace (iterator_position, Args&&... args);

The function accepts two mandatory parameters which are specified as below.

  1. iterator_position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
  2. args – It specifies the element to be inserted in the vector container.

vector::emplace_back()

The emplace_back() function is used to insert a new element into the vector container; the new item is added to the end of the vector.

Syntax

vector.emplace_back(value)

The value to be inserted into the vector is passed as the parameter.

C++ Vector Modifiers Example

See the following code example of C++ Vector Modifiers.

#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main()
{
	vector<int>v1;
	//assign the vector with 5 times 50
	v1.assign(5,50);
	cout<<"After assign the vector is: ";
	for(int i=0;i<v1.size();i++)
	{
		//v1.size() will return size of vector
		cout<<v1[i]<<" ";
	}
	cout<<"\n";
	//====================================================================================//
	
	//insert 100 at the last of the vector
	//using push_back()
	v1.push_back(100);
	int n=v1.size();
	cout<<"The last element of the vector right now is: "<<v1[n-1]<<" and size: "<<n<<"\n";
	
	//====================================================================================//
	
	//delete the last element of the vector
	//using pop_back()
	v1.pop_back();
	n=v1.size();
	cout<<"After removing the size of vector is "<<n<<" & last element is "<<v1[n-1]<<"\n";
	
	//====================================================================================//
	
	//insert 70 at the front of the vector
	//using insert()
	v1.insert(v1.begin(),70);
	cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";
	
	//======================================================================================//
	
	//remove the first element using erase
	v1.erase(v1.begin());
	cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";
	
	//=====================================================================================//
	
	//swap first and last element of the vector
	//using swap()
	n=v1.size();
	cout<<"Before swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n";
	swap(v1[0],v1[n-1]);
	cout<<"After swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n";
	
	//======================================================================================//
	
	//insert element at front using emplace()
	v1.emplace(v1.begin(),12);
	v1.emplace(v1.begin(),12);
	cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";
	
	//=======================================================================================//
	
	//insert element at the back of the vector
	//using emplace_back()
	v1.emplace_back(60);
	n=v1.size();
	cout<<"After inserting at back of the back value is: "<<v1[n-1]<<"\n";
	
	//========================================================================================//
	
	//clear all the element of the vector
	v1.clear();
	n=v1.size();
	cout<<"After clearing the size of vector is: "<<n<<"\n";
	
	//================================================================================================//
	return 0;
}

The output is following.

C++ Vector Modifiers Example

 

Here one thing to note that emplace() and emplace_back() works on c++11 or above. So if your version is lower, then it might not work.

C++ Vector Iterators

The Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. See some below vector iterators.

vector::begin()

The begin() function is used to return an iterator pointing to the first element of the vector container.

Syntax

vector.begin()

vector::end()

The end() function is used to return an iterator pointing to next to the last element of the vector container. 

Syntax

vector.end()

vector::cbegin()

The function returns an iterator which is used to iterate container.

  1. The iterator points to the beginning of the vector.
  2. Iterator cannot modify the contents of the vector.

Syntax

vector.cbegin()

vector::cend()

The cend() function returns an iterator which is used to iterate container.

  1. The iterator points to the past-the-end element of the vector.
  2. Iterator cannot modify the contents of the vector.

Syntax

vector.cend()

vector::crbegin()

It returns the const_reverse_iterator pointing to the last element in the container. Means this will return the last element of the vector.

Syntax

const_reverse_iterator crbegin() const noexcept;

vector::crend()

It’s a public member function that returns a const_reverse_iterator pointing to the element preceding the first element.

Syntax

const_reverse_iterator crend() const noexcept;

vector::rbegin()

The vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container.

Syntax

vector.rbegin()

vector::rend()

The vector::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the array container.

Syntax

vector.rend()

Vector Iterators Example

See the following iterators example in C++ Vector.

#include <iostream> 
#include <vector> 
using namespace std; 
int main() 
{ 

	//First insert some element to the vector
    vector<int> v1;
    int n,x;
    cout<<"Enter the size of the vector: ";
    cin>>n;
    cout<<"Enter vector values:\n";
    for (int j=0;j<n;j++)
	{
		cin>>x;
		v1.push_back(x);
	} 
	//================Print all element using begin() & end()==========================//
    cout<<"Output of all elements using begin() & end(): "; 
    for (auto i =v1.begin(); i!=v1.end();++i) 
        cout<<*i<<" "; 
  //=====================Print all element using cbegin() & cend()======================//
    cout<<"\nOutput of all elements using cbegin and cend: "; 
    for (auto i=v1.cbegin();i!=v1.cend(); ++i) 
        cout<<*i<<" "; 

  //====================Print all element using crbegin() & crend()===================//
    cout<<"\nOutput of all elements using crbegin and crend: ";
    for (auto i=v1.crbegin();i!=v1.crend();++i) 
        cout<<*i<<" "; 
  //=====================Print all element using rbegin() & rend()==========================//
    cout<<"\nOutput of all elements using rbegin and rend: "; 
    for (auto i=v1.rbegin();i!=v1.rend();++i) 
        cout<<*i<<" "; 
  //========================================================================================//
    return 0; 
}

The output is following.

Vector Iterators Example

 

C++ Vector Capacity

Vector capacity returns the size of allocated storage capacity. It returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

The capacity is not necessarily equal to the vector size. It can be similar or higher, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.

See some of the capacity functions in vector.

vector::size()

The size() function is used to return the size of the vector container or the number of elements in the vector container. It returns the size of the vector.

Syntax

vector.size()

vector::max_size()

It returns the maximum size of the vector. The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container.

Syntax

vector.max_size()

vector::resize()

It is used to change the size of the vector. The resize() function alters the container’s content in actual by inserting or deleting the elements from it.

Syntax

vector.resize(int n, int value)
  1. n: it is a new container size, expressed in the number of elements.
  2. value: if this parameter is specified then new elements are initialized with this value.

vector::capacity()

It returns the size of the allocated storage capacity. The vector::capacity() function is the built-in function which returns the size of the storage space currently allocated for a vector, expressed in terms of items.

Syntax

vector.capacity()

vector::empty()

The empty() function is used to check if the vector container is empty or not. It is used to test whether the vector is empty.

Syntax

vector.empty()

vector::reserve()

The reserve() function helps the user specify the minimum size of the vector. It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.

Syntax

vector.reserve(n)

Argument n which denotes the no of elements to be stored in a vector.

vector::shrink_to_fit()

The vector::shrink_to_fit() function reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.

Syntax

vector.shrink_to_fit()

Vector Iterator Program in C++

#include<iostream> 
#include<vector> 
using namespace std; 
int main() 
{ 
	//First insert some element to the vector
    vector<int> v1;
    int n,x;
    cout<<"Enter the size of the vector: ";
    cin>>n;
    cout<<"Enter vector values:\n";
    for (int j=0;j<n;j++)
	{
		cin>>x;
		v1.push_back(x);
	}
	//=======================Demonstrate size()===============================//
	
	cout<<"Size of the vector is: "<<v1.size()<<"\n";
	
	//======================Demonstrate max_size()=======================================// 
	
	cout<<"\nMax_Size of the vector is: "<<v1.max_size(); 
	
	//======================Demonstrate capacity()======================================//
	
	cout<<"\nCapacity of the vector is: "<<v1.capacity();
	
	//======================Resize the vector to n-2===================================//
	
	v1.resize(n-2);  
	cout<<"\nAfter resize the Size of the vector is: "<<v1.size(); 
	
	//=====================Demonstrate reserve() =====================================//
	cout<<"\nBefore reserve the size of the vector is: "<<v1.size();
	cout<<"\nBefore reserve the capacity of the vector is: "<<v1.capacity();
	v1.reserve(40);
	cout<<"\nAfter reserve the capacity of the vector is: "<<v1.capacity();
	cout<<"\nAfter reserve the size of the vector is: "<<v1.size();
	//======================Shrink the vector==========================================//
	v1.shrink_to_fit(); 
	cout << "\nVector elements are: "; 
	for (auto i=v1.begin();i!=v1.end();i++) 
		cout<<*i<<" "; 
	//=====================Clear all elements and check if the vector is empty================//
	v1.clear();
	if (v1.empty() == false) 
		cout<<"\nVector is not empty"; 
	else
		cout<<"\nVector is empty";
	//============================================================================================//
	return 0; 
} 

The output is following.

Vector Iterator Program in C++

 

Element access in C++ Vector

 Here, we will discuss different techniques to get an element from the vector by index or position. We will see some of the methods that can use to access the element in the vector.

vector::operator[ ]

The operator is used to reference the element present at a position given inside the operator. It accesses the specified element at position i.

Syntax

vectorname[position]

The position argument is the position of the element to be fetched.

vector::at()

The at() function is used reference the element present at the position given as the parameter to the function.

Syntax

vector.at(position)

It is the position of the element to be fetched. It provides a reference to an element.

vector::front()

The front() function can be used to fetch the first element of a vector container. Returns the reference to the first element of the vector.

Syntax

vector.front()

vector::back()

The back() function can be used to fetch the last element of a vector container. Returns the reference to the last element of the vector.

Syntax

vector.back()

vector::data()

It writes the data of the vector into the array. The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.

Syntax

vector.data()

 Now, see the below C++ program.

#include<iostream>
#include<vector> 
using namespace std; 
int main() 
{ 
	//==================First insert some element to the vector==========================//
    vector<int>v1;
    int n,x;
    cout<<"Enter the size of the vector: ";
    cin>>n;
    cout<<"Enter vector values:\n";
    for (int j=0;j<n;j++)
	{
		cin>>x;
		v1.push_back(x);
	}
	//================== Show value at position 2 using Reference Operator ==============//
	
	cout<<"\nReference operator v1[2]= "<<v1[2]; 
	
	//================== Show value at position 3 using at() =======================//
	
	cout<<"\nValue at position 3 is: "<<v1.at(3); 

	//===================Show the first element of the vector========================//
	cout <<"\nFirst element of the vector is: "<<v1.front(); 

	//================Show the last element of the vector===========================//
	cout << "\nLast element of the vector is: "<<v1.back(); 
	
	//================Showing all the elements  using data==========================// 
	int* i=v1.data();
	cout<<"\nAll the elements of the vector is:\n";
	for(int j=0;j<v1.size();j++)
	{
		cout<<*i++<<" ";
	}
	return 0; 
} 

The output of the above C++ program is following.

Element access in C++ Vector

 

Conclusively, C++ Vector Tutorial With Example | Vector in C++ STL post is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.