Coders Packet

Vector in C++ Standard Template Library (STL)

By Rahul Chandrakant Suthar

In this tutorial, we will learn about vectors and their functions in C++ programming.

Vectors are utilized in C++ to store elements of comparable data types. However, unlike arrays, vectors can grow in size dynamically.

This means you'll be able to resize the vector while the program is running to fit your needs.

The C++ Standard Template Library includes vectors.

To use vectors, you want to include the vector header files in your program.

When to Use a Vector?

A C++ vector should be used when:

  • When dealing with constantly changing data elements.
  • If you don't know the size of your data before you start, vectors don't require you to set a maximum container size.
#include 

Vector declaration in C++

After including the header file, here's the way to declare a vector in C++:

vector variable_name;

The indicates the vector type. Primitive data types like int, char, and float may be used. As an example,

vector n;

Here, n is the name of the vector.

Notice that we didn't specify the size of the vector during the declaration. This is because the vector size can grow dynamically and does not need to be defined.

 

   INPUT:

#include<bits/stdc++.h>

using namespace std;

int main() {
  vector < int > v;
 //pushback
  for (int j = 0; j < 10; j++) {
    v.push_back(j); //inserting elements in the vector
  }

  cout << "the elements in the vector: ";
  for (auto it = v.begin(); it != v.end(); it++)
    cout << * it << " ";
  //fromt
  cout << "\nThe front element of the vector: " << v.front();
  //back
  cout << "\nThe last element of the vector: " << v.back();
  //size
  cout << "\nThe size of the vector: " << v.size();
  //pop
  cout << "\nDeleting element from the end: " << v[v.size() - 1];
  v.pop_back();
  
  cout << "\nPrinting the vector after removing the last element:" << endl;
  for (int i = 0; i < v.size(); i++)
    cout << v[i] << " ";
  //insert
  cout << "\nInserting 5 at the beginning:" << endl;
  v.insert(v.begin(), 5);
  cout << "The first element is: " << v[0] << endl;
  //erase
  cout << "Erasing the first element" << endl;
  v.erase(v.begin());
  cout << "Now the first element is: " << v[0] << endl;
  //empty
  if (v.empty())
    cout << "\nvector is empty";
  else
    cout << "\nvector is not empty" << endl;

  v.clear();
  cout << "Size of the vector after clearing the vector: " << v.size();

}

 

 

     Output:

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Rahul Chandrakant Suthar (Rahulcs27)

Download packets of source code on Coders Packet