Vectors in C++

As we know that the C++ programming language offers various useful features and functionalities to the programmers. In C++, Vectors are one of the important and exciting features. You can say that vectors are the same as the array. When an element is inserted or deleted, it can automatically resize itself.

What are vectors in C++?

IN C++, vectors are dynamic arrays that are used to store data. It is capable of resizing itself automatically. When you insert or delete an element then the resizing takes place. Arrays are static in nature and also it is used to store sequential data. But vectors offer more flexibility and efficiency to the program.

In vectors, the storage is handled automatically by the containers. The elements of the vectors are stored in contiguous storage. That’s why it becomes easy to access and traverse the vector elements using iterators.

Are vectors ordered in C++?

No, vectors are not ordered in C++. If you insert data then that data will be inserted at the end of it. So, it takes different times to insert data at the end and sometimes there may be a need to extend the vector. You can easily traverse and access the vector elements using iterators because they are stored in adjacent storage.

Difference between vector and array

Arrays are static in nature. It means that you cannot change the size at runtime. But vectors are dynamic in nature. While inserting or deleting an element, it automatically resizes itself.

When to use a vector

You can make use of vectors on the following situations:-

  • Data elements that change consistently.
  • If you do not know the size of data at the beginning.

Initializing vectors in C++

Syntax:-

vector <data-type> variable_name (items)

First, we have to use the vector keyword at the beginning. Then, mention the data type of the elements which will be stored in vectors. Then, provide the name of the vector or the data elements. The items specify the number of elements for the vector’s data.

How the vectors are stored in C++

Below, we created a blank vector:-

#include <vector>
int main()
{
    std::vector<int> v1;
}

Vectors are dynamic in nature.

Member functions of vectors in C++

In STL, a vector container offers various useful functions.

  • Modifiers
  • Iterators
  • Capacity

Modifiers in C++

Mainly used to change the meaning of the specified data type. Below are the common modifiers in C++:-

  • push_back():- Mainly used to push the element from the back.
  • assign():- Used for assigning new values to the vector elements.
  • insert():- Mainly used for inserting new elements in a vector at specified location.
  • pop_back():- Used to remove the vector elements from the back.
  • erase():- Used to remove a range of vector elements from a specified location.
  • clear():- Removes all the vector elements.
  • swap():- Mainly used to swap contents of one vector with another vector of the same data type.

Example:-

#include <bits/stdc++.h>
#include <vector>
using namespace std;
   
int main()
{
  vector<int> v1;
   
  v1.assign(4, 6);
  cout << "TechVidvan Tutorial: C++ Vectors!\n\n";
   
  cout << "Vector elements are: ";
  for (int i = 0; i < 4; i++)
    	cout << v1[i] << " ";

  v1.push_back(15);
  int s = v1.size();
  cout << "\nLast element is: " << v1[s - 1];
 
  cout << "\nVector elements after push back are: ";
  for (int i = 0; i < v1.size(); i++)
  cout << v1[i] << " ";
   
  v1.pop_back();

  cout << "\nVector elements after pop_back are: ";
  for (int i = 0; i < v1.size(); i++)
    	cout << v1[i] << " ";
  v1.insert(v1.begin(), 11);
   
  cout << "\nFirst element after insertion is: " << v1[0];
  v1.erase(v1.begin());
   
  cout << "\nFirst element after erasing is: " << v1[0];
 
  v1.emplace(v1.begin(), 7);
  cout << "\nFirst element emplace is: " << v1[0];
   
  v1.emplace_back(13);
  s = v1.size();
  cout << "\nLast element after emplace_back: " << v1[s - 1];
 
  v1.clear();
  cout << "\nVector size after clear is: " << v1.size();
   
 
  vector<int> o1, o2;
  o1.push_back(2);
  o1.push_back(3);
  o2.push_back(5);
  o2.push_back(7);

   cout << "\nBefore Swapping";
  cout << "\n\nVector 1-> ";
  for (int i = 0; i < o1.size(); i++)
    	cout << o1[i] << " ";
   
  cout << "\n\nVector 2-> ";
  for (int i = 0; i < o2.size(); i++)
    	cout << o2[i] << " ";

  o1.swap(o2);
   
  cout << "\nAfter Swapping \n\nVector 1-> ";
  for (int i = 0; i < o1.size(); i++)
    	cout << o1[i] << " ";
   
  cout << "\n\nVector 2-> ";
  for (int i = 0; i < o2.size(); i++)
    	cout << o2[i] << " ";
}

Output:-

TechVidvan Tutorial: C++ Vectors!

Vector elements are: 6 6 6 6
Last element is: 15
Vector elements after push back are: 6 6 6 6 15
Vector elements after pop_back are: 6 6 6 6
First element after insertion is: 11
First element after erasing is: 6
First element emplace is: 7
Last element after emplace_back: 13
Vector size after clear is: 0
Before Swapping

Vector 1-> 2 3

Vector 2-> 5 7
After Swapping

Vector 1-> 5 7

Vector 2-> 2 3

Iterators in C++

Mainly used to access the elements which are stored in a vector. Below are the common iterators:-

  • begin():- Returns an iterator which will point to the first element in the vector.
  • end():- Returns an iterator which points to the last element in the vector.
  • cbegin():- It is similar to the begin() function. But it cannot modify elements.
  • cend():- It is similar to the end() function. But it cannot modify elements.

Example:-

#include <iostream>
#include <vector>
   
using namespace std;
   
int main()
{
  vector<int> v1;
   
  for (int i = 2; i <= 8; i++)
    	v1.push_back(i);
   
  cout << "TechVidvan Tutorial: C++ Vectors" << endl;
  cout << "Elements are:" << endl;
  for (auto i = v1.begin(); i != v1.end(); ++i)
    	cout << *i << " ";
 
  return 0;
}

Output:-

TechVidvan Tutorial: C++ Vectors
Elements are:
2 3 4 5 6 7 8

Capacity in C++

Helps you in determining the capacity of a vector.

  • Size():- Used for getting the number of items in a vector.
  • Max_size():- Used to return the highest number of items that is stored in a vector.
  • Capacity():- Returns the size of the storage space allocated to the vector.
  • resize():- Mainly used to resize the container so that it can have ‘n’ elements.
  • empty():- Returns true if the vector is empty.

Example:-

#include <iostream>
#include <vector>
   
using namespace std;
   
int main()
{
  vector<int> v1;
   
  for (int i = 5; i <= 15; i++)
    	v1.push_back(i);
   
  cout << "Size of the vector-> " << v1.size();
  cout << "\nCapacity of the vector-> " << v1.capacity();
  cout << "\nMax Size of the vector-> " << v1.max_size();
 
  v1.resize(5);
  cout << "\nSize of the vector after resizing-> " << v1.size();
   
  if (v1.empty() == false)
    	cout << "\nThe Vector is not empty";
  else
    	cout << "\nThe Vector is empty";
   
  return 0;
}

Output:-

Size of the vector-> 11
Capacity of the vector-> 16
Max Size of the vector-> 2305843009213693951
Size of the vector after resizing-> 5
The Vector is not empty

Element access in C++

  • at(position):- Used for returning a reference to the element at the given position in the vector.
  • front():- Used to return a reference to the first element in the vector.
  • back():- Used to return a reference to the last element in the vector.
  • data():- Used to return a direct pointer to the memory array.
  • reference operator[pos]:- Used for returning a reference to the element in a vector at a given position.

Example:-

#include <bits/stdc++.h>
using namespace std;
int main()
{
  vector<int> v1;
 
  for (int i = 2; i <= 7; i++)
    	v1.push_back(i * 4);
 
  cout << "\nReference operator[pos]: v1[2]-> " << v1[2];
 
  cout << "\nat: v1.at(3)-> " << v1.at(3);
 
  cout << "\nfront(): v1.front()-> " << v1.front();
 
  cout << "\nback(): v1.back()-> " << v1.back();

  int* data = v1.data();
 
  cout << "\nThe first element is-> " << *data;
  return 0;
}

Output:-

Reference operator[pos]: v1[2]-> 16
at: v1.at(3)-> 20
front(): v1.front()-> 8
back(): v1.back()-> 28
The first element is-> 8

Summary

In this tutorial, we discussed the vectors in C++ and how to initialize them. We also discussed the difference between arrays and vectors. Then we saw about the member functions of vectors in C++ and when you should use a vector in C++.