C++ Vector: The Complete Guide

0
843
Vector in C++ STL

C++ Vector is a template class that perfectly replaces suitable old C-style arrays. It allows the same natural syntax used with plain arrays. In addition, it offers a series of services that free the C++ programmer from taking care of the allocated memory and consistently operating on the contained objects.

C++ STL

C++ STL (Standard Template Library) is a robust 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

C++ Vector is a built-in sequence of containers that can be changed dynamically. In Vector, you can change its size any time you want. Like an array, it also takes a contiguous memory location, but the difference is Vector is dynamic, whereas an Array is not.

The first step in 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 Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace std. Therefore, you must 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;
}

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 gives 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. Then, it adds an element at the end of the Vector. Finally, 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, which 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 removes 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 the 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 the container by inserting the new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one. Finally, 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 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 the 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 the same as dynamic arrays, with the ability to resize themselves automatically when an element is inserted or deleted. Their storage is handled automatically by the container. See some below vector iterators.

vector::begin()

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

Syntax

vector.begin()

vector::end()

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

Syntax

vector.end()

vector::cbegin()

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

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

Syntax

vector.cbegin()

vector::cend()

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

  1. The iterator points to the past-the-end element of the Vector.
  2. The 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. This means this will return the last element of the Vector.

Syntax

const_reverse_iterator crbegin() const noexcept;

vector::crend()

A public member function 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 that 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 the following.

Vector Iterators Example

C++ Vector Capacity

Vector capacity returns the size of the allocated storage capacity. In addition, 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 growth without reallocating 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 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 actual content 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, 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 that 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 checks whether the vector container is empty. 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 to store at least the number of the selected elements without reallocating memory.

Syntax

vector.reserve(n)

Argument n 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 the 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. Then, 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 to 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 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 fetch the last element of a vector container. Returns the reference to the previous 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 the following.

Element access in C++ Vector

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

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